0026798: Boolean operations: keep desired cells and boundaries in the result
[occt.git] / src / DrawResources / TestCommands.tcl
1 # Copyright (c) 2013-2014 OPEN CASCADE SAS
2 #
3 # This file is part of Open CASCADE Technology software library.
4 #
5 # This library is free software; you can redistribute it and/or modify it under
6 # the terms of the GNU Lesser General Public License version 2.1 as published
7 # by the Free Software Foundation, with special exception defined in the file
8 # OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
9 # distribution for complete text of the license and disclaimer of any warranty.
10 #
11 # Alternatively, this file may be used under the terms of Open CASCADE
12 # commercial license or contractual agreement.
13
14 ############################################################################
15 # This file defines scripts for execution of OCCT tests.
16 # It should be loaded automatically when DRAW is started, and provides
17 # top-level commands starting with 'test'. Type 'help test' to get their
18 # synopsys.
19 # See OCCT Tests User Guide for description of the test system.
20 #
21 # Note: procedures with names starting with underscore are for internal use 
22 # inside the test system.
23 ############################################################################
24
25 # Default verbose level for command _run_test
26 set _tests_verbose 0
27
28 # regexp for parsing test case results in summary log
29 set _test_case_regexp {^CASE\s+([\w.-]+)\s+([\w.-]+)\s+([\w.-]+)\s*:\s*([\w]+)(.*)}
30
31 # Basic command to run indicated test case in DRAW
32 help test {
33   Run specified test case
34   Use: test group grid casename [options...]
35   Allowed options are:
36   -echo: all commands and results are echoed immediately,
37          but log is not saved and summary is not produced
38          It is also possible to use "1" instead of "-echo"
39          If echo is OFF, log is stored in memory and only summary
40          is output (the log can be obtained with command "dlog get")
41   -outfile filename: set log file (should be non-existing),
42          it is possible to save log file in text file or
43          in html file(with snapshot), for that "filename"
44          should have ".html" extension
45   -overwrite: force writing log in existing file
46   -beep: play sound signal at the end of the test
47   -errors: show all lines from the log report that are recognized as errors
48          This key will be ignored if the "-echo" key is already set.
49 }
50 proc test {group grid casename {args {}}} {
51     # set default values of arguments
52     set echo 0
53     set errors 0
54     set logfile ""
55     set overwrite 0
56     set signal 0
57
58     # get test case paths (will raise error if input is invalid)
59     _get_test $group $grid $casename dir gridname casefile
60
61     # check arguments
62     for {set narg 0} {$narg < [llength $args]} {incr narg} {
63         set arg [lindex $args $narg]
64         # if echo specified as "-echo", convert it to bool
65         if { $arg == "-echo" || $arg == "1" } {
66             set echo t
67             continue
68         }
69
70         # output log file
71         if { $arg == "-outfile" } {
72             incr narg
73             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } {
74                 set logfile [lindex $args $narg]
75             } else {
76                 error "Option -outfile requires argument"
77             }
78             continue
79         }
80
81         # allow overwrite existing log
82         if { $arg == "-overwrite" } {
83             set overwrite 1
84             continue
85         }
86
87         # sound signal at the end of the test
88         if { $arg == "-beep" } {
89             set signal t
90             continue
91         }
92
93         # if errors specified as "-errors", convert it to bool
94         if { $arg == "-errors" } {
95             set errors t
96             continue
97         }
98
99         # unsupported option
100         error "Error: unsupported option \"$arg\""
101     }
102     # run test
103     uplevel _run_test $dir $group $gridname $casefile $echo 
104
105     # check log
106     if { !$echo } {
107         _check_log $dir $group $gridname $casename $errors [dlog get] summary html_log
108
109         # create log file
110         if { ! $overwrite && [file isfile $logfile] } {
111             error "Error: Specified log file \"$logfile\" exists; please remove it before running test or use -overwrite option"
112         }
113         if {$logfile != ""} {
114             if {[file extension $logfile] == ".html"} {
115                 if {[regexp {vdump ([^\s\n]+)} $html_log dump snapshot]} {
116                     catch {file copy -force $snapshot [file rootname $logfile][file extension $snapshot]}
117                 }
118                 _log_html $logfile $html_log "Test $group $grid $casename"
119             } else {
120                 _log_save $logfile "[dlog get]\n$summary" "Test $group $grid $casename"
121             }
122         }
123     }
124
125     # play sound signal at the end of test
126     if {$signal} {
127         puts "\7\7\7\7"
128     }
129     return
130 }
131
132 # Basic command to run indicated test case in DRAW
133 help testgrid {
134   Run all tests, or specified group, or one grid
135   Use: testgrid [groupmask [gridmask [casemask]]] [options...]
136   Allowed options are:
137   -parallel N: run N parallel processes (default is number of CPUs, 0 to disable)
138   -refresh N: save summary logs every N seconds (default 600, minimal 1, 0 to disable)
139   -outdir dirname: set log directory (should be empty or non-existing)
140   -overwrite: force writing logs in existing non-empty directory
141   -xml filename: write XML report for Jenkins (in JUnit-like format)
142   -beep: play sound signal at the end of the tests
143   Groups, grids, and test cases to be executed can be specified by list of file 
144   masks, separated by spaces or comma; default is all (*).
145 }
146 proc testgrid {args} {
147     global env tcl_platform _tests_verbose
148
149     ######################################################
150     # check arguments
151     ######################################################
152
153     # check that environment variable defining paths to test scripts is defined
154     if { ! [info exists env(CSF_TestScriptsPath)] || 
155         [llength $env(CSF_TestScriptsPath)] <= 0 } {
156         error "Error: Environment variable CSF_TestScriptsPath is not defined"
157     }
158
159     # treat options
160     set parallel [_get_nb_cpus]
161     set refresh 60
162     set logdir ""
163     set overwrite 0
164     set xmlfile ""
165     set signal 0
166     for {set narg 0} {$narg < [llength $args]} {incr narg} {
167         set arg [lindex $args $narg]
168
169         # parallel execution
170         if { $arg == "-parallel" } {
171             incr narg
172             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
173                 set parallel [expr [lindex $args $narg]]
174             } else {
175                 error "Option -parallel requires argument"
176             }
177             continue
178         }
179
180         # refresh logs time
181         if { $arg == "-refresh" } {
182             incr narg
183             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
184                 set refresh [expr [lindex $args $narg]]
185             } else {
186                 error "Option -refresh requires argument"
187             }
188             continue
189         }
190
191         # output directory
192         if { $arg == "-outdir" } {
193             incr narg
194             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
195                 set logdir [lindex $args $narg]
196             } else {
197                 error "Option -outdir requires argument"
198             }
199             continue
200         }
201
202         # allow overwrite logs 
203         if { $arg == "-overwrite" } {
204             set overwrite 1
205             continue
206         }
207
208         # refresh logs time
209         if { $arg == "-xml" } {
210             incr narg
211             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
212                 set xmlfile [lindex $args $narg]
213             }
214             if { $xmlfile == "" } {
215                 set xmlfile TESTS-summary.xml
216             }
217             continue
218         }
219
220         # sound signal at the end of the test
221         if { $arg == "-beep" } {
222             set signal t
223             continue
224         }
225
226         # unsupported option
227         if { [regexp {^-} $arg] } {
228             error "Error: unsupported option \"$arg\""
229         }
230
231         # treat arguments not recognized as options as group and grid names
232         if { ! [info exists groupmask] } {
233             set groupmask [split $arg ,]
234         } elseif { ! [info exists gridmask] } {
235             set gridmask [split $arg ,]
236         } elseif { ! [info exists casemask] } {
237             set casemask [split $arg ,]
238         } else {
239             error "Error: cannot interpret argument $narg ($arg)"
240         }
241     }
242
243     # check that target log directory is empty or does not exist
244     set logdir [file normalize [string trim $logdir]]
245     if { $logdir == "" } {
246         # if specified logdir is empty string, generate unique name like 
247         # results/<branch>_<timestamp>
248         set prefix ""
249         if { ! [catch {exec git branch} gitout] &&
250              [regexp {[*] ([\w]+)} $gitout res branch] } {
251             set prefix "${branch}_"
252         }
253         set logdir "results/${prefix}[clock format [clock seconds] -format {%Y-%m-%dT%H%M}]"
254         set logdir [file normalize $logdir]
255     }
256     if { [file isdirectory $logdir] && ! $overwrite && ! [catch {glob -directory $logdir *}] } {
257         error "Error: Specified log directory \"$logdir\" is not empty; please clean it before running tests"
258     } 
259     if { [catch {file mkdir $logdir}] || ! [file writable $logdir] } {
260         error "Error: Cannot create directory \"$logdir\", or it is not writable"
261     }
262
263     # masks for search of test groups, grids, and cases
264     if { ! [info exists groupmask] } { set groupmask * }
265     if { ! [info exists gridmask ] } { set gridmask  * }
266     if { ! [info exists casemask ] } { set casemask  * }
267
268     ######################################################
269     # prepare list of tests to be performed
270     ######################################################
271
272     # list of tests, each defined by a list of:
273     # test scripts directory
274     # group (subfolder) name
275     # grid (subfolder) name
276     # test case name
277     # path to test case file
278     set tests_list {}
279
280     # iterate by all script paths
281     foreach dir [lsort -unique [_split_path $env(CSF_TestScriptsPath)]] {
282         # protection against empty paths
283         set dir [string trim $dir]
284         if { $dir == "" } { continue }
285
286         if { $_tests_verbose > 0 } { _log_and_puts log "Examining tests directory $dir" }
287
288         # check that directory exists
289         if { ! [file isdirectory $dir] } {
290             _log_and_puts log "Warning: directory $dir listed in CSF_TestScriptsPath does not exist, skipped"
291             continue
292         }
293
294         # search all directories in the current dir with specified mask
295         if [catch {glob -directory $dir -tail -types d {*}$groupmask} groups] { continue }
296
297         # iterate by groups
298         if { $_tests_verbose > 0 } { _log_and_puts log "Groups to be executed: $groups" }
299         foreach group [lsort -dictionary $groups] {
300             if { $_tests_verbose > 0 } { _log_and_puts log "Examining group directory $group" }
301
302             # file grids.list must exist: it defines sequence of grids in the group
303             if { ! [file exists $dir/$group/grids.list] } {
304                 _log_and_puts log "Warning: directory $dir/$group does not contain file grids.list, skipped"
305                 continue
306             }
307
308             # read grids.list file and make a list of grids to be executed
309             set gridlist {}
310             set fd [open $dir/$group/grids.list]
311             set nline 0
312             while { [gets $fd line] >= 0 } {
313                 incr nline
314
315                 # skip comments and empty lines
316                 if { [regexp "\[ \t\]*\#.*" $line] } { continue }
317                 if { [string trim $line] == "" } { continue }
318
319                 # get grid id and name
320                 if { ! [regexp "^\(\[0-9\]+\)\[ \t\]*\(\[A-Za-z0-9_.-\]+\)\$" $line res gridid grid] } {
321                     _log_and_puts log "Warning: cannot recognize line $nline in file $dir/$group/grids.list as \"gridid gridname\"; ignored"
322                     continue
323                 }
324
325                 # check that grid fits into the specified mask
326                 foreach mask $gridmask {
327                     if { $mask == $gridid || [string match $mask $grid] } {
328                         lappend gridlist $grid
329                     }
330                 }
331             }
332             close $fd
333
334             # iterate by all grids
335             foreach grid $gridlist {
336
337                 # check if this grid is aliased to another one
338                 set griddir $dir/$group/$grid
339                 if { [file exists $griddir/cases.list] } {
340                     set fd [open $griddir/cases.list]
341                     if { [gets $fd line] >= 0 } {
342                         set griddir [file normalize $dir/$group/$grid/[string trim $line]]
343                     }
344                     close $fd
345                 }
346
347                 # check if grid directory actually exists
348                 if { ! [file isdirectory $griddir] } { 
349                     _log_and_puts log "Error: tests directory for grid $grid ($griddir) is missing; skipped"
350                     continue 
351                 }
352
353                 # create directory for logging test results
354                 if { $logdir != "" } { file mkdir $logdir/$group/$grid }
355
356                 # iterate by all tests in the grid directory
357                 if { [catch {glob -directory $griddir -type f {*}$casemask} testfiles] } { continue }
358                 foreach casefile [lsort -dictionary $testfiles] {
359                     # filter out files with reserved names
360                     set casename [file tail $casefile]
361                     if { $casename == "begin" || $casename == "end" ||
362                          $casename == "parse.rules" } {
363                         continue
364                     }
365
366                     lappend tests_list [list $dir $group $grid $casename $casefile]
367                 }
368             }
369         }
370     }
371     if { [llength $tests_list] < 1 } {
372         error "Error: no tests are found, check you input arguments and variable CSF_TestScriptsPath!"
373     } else {
374         puts "Running tests (total [llength $tests_list] test cases)..."
375     }
376
377     ######################################################
378     # run tests
379     ######################################################
380     
381     # log command arguments and environment
382     lappend log "Command: testgrid $args"
383     lappend log "Host: [info hostname]"
384     lappend log "Started on: [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S}]"
385     catch {lappend log "DRAW build:\n[dversion]" }
386     lappend log "Environment:"
387     foreach envar [lsort [array names env]] {
388         lappend log "$envar=\"$env($envar)\""
389     }
390     lappend log ""
391
392     set refresh_timer [clock seconds]
393     uplevel dchrono _timer reset
394     uplevel dchrono _timer start
395
396     # if parallel execution is requested, allocate thread pool
397     if { $parallel > 0 } {
398         if { ! [info exists tcl_platform(threaded)] || [catch {package require Thread}] } {
399             _log_and_puts log "Warning: Tcl package Thread is not available, running in sequential mode"
400             set parallel 0
401         } else {
402             set worker [tpool::create -minworkers $parallel -maxworkers $parallel]
403             # suspend the pool until all jobs are posted, to prevent blocking of the process
404             # of starting / processing jobs by running threads
405             catch {tpool::suspend $worker}
406             if { $_tests_verbose > 0 } { _log_and_puts log "Executing tests in (up to) $parallel threads" }
407             # limit number of jobs in the queue by reasonable value
408             # to prevent slowdown due to unnecessary queue processing
409             set nbpooled 0
410             set nbpooled_max [expr 10 * $parallel]
411             set nbpooled_ok  [expr  5 * $parallel]
412         }
413     }
414
415     # start test cases
416     set userbreak 0
417     foreach test_def $tests_list {
418         # check for user break
419         if { $userbreak || "[info commands dbreak]" == "dbreak" && [catch dbreak] } {
420             set userbreak 1
421             break
422         }
423
424         set dir       [lindex $test_def 0]
425         set group     [lindex $test_def 1]
426         set grid      [lindex $test_def 2]
427         set casename  [lindex $test_def 3]
428         set casefile  [lindex $test_def 4]
429
430         # command to set tests for generation of image in results directory
431         set imgdir_cmd ""
432         if { $logdir != "" } { set imgdir_cmd "set imagedir $logdir/$group/$grid" }
433
434         # prepare command file for running test case in separate instance of DRAW
435         set fd_cmd [open $logdir/$group/$grid/${casename}.tcl w]
436         puts $fd_cmd "$imgdir_cmd"
437         puts $fd_cmd "set test_image $casename"
438         puts $fd_cmd "_run_test $dir $group $grid $casefile t"
439
440         # use dlog command to obtain complete output of the test when it is absent (i.e. since OCCT 6.6.0)
441         # note: this is not needed if echo is set to 1 in call to _run_test above
442         if { ! [catch {dlog get}] } {
443             puts $fd_cmd "puts \[dlog get\]"
444         } else {
445             # else try to use old-style QA_ variables to get more output...
446             set env(QA_DUMP) 1
447             set env(QA_DUP) 1
448             set env(QA_print_command) 1
449         }
450
451         # final 'exit' is needed when running on Linux under VirtualGl
452         puts $fd_cmd "exit"
453         close $fd_cmd
454
455         # commant to run DRAW with a command file;
456         # note that empty string is passed as standard input to avoid possible 
457         # hang-ups due to waiting for stdin of the launching process
458         set command "exec <<{} DRAWEXE -f $logdir/$group/$grid/${casename}.tcl"
459
460         # alternative method to run without temporary file; disabled as it needs too many backslashes
461         # else {
462         # set command "exec <<\"\" DRAWEXE -c $imgdir_cmd\\\; set test_image $casename\\\; \
463         # _run_test $dir $group $grid $casefile\\\; \
464         # puts \\\[dlog get\\\]\\\; exit"
465         # }
466
467         # run test case, either in parallel or sequentially
468         if { $parallel > 0 } {
469             # parallel execution
470             set job [tpool::post -nowait $worker "catch \"$command\" output; return \$output"]
471             set job_def($job) [list $logdir $dir $group $grid $casename]
472             incr nbpooled
473             if { $nbpooled > $nbpooled_max } {
474                 _testgrid_process_jobs $worker $nbpooled_ok
475             }
476         } else {
477             # sequential execution
478             catch {eval $command} output
479             _log_test_case $output $logdir $dir $group $grid $casename log
480
481             # update summary log with requested period
482             if { $logdir != "" && $refresh > 0 && [expr [clock seconds] - $refresh_timer > $refresh] } {
483                 # update and dump summary
484                 _log_summarize $logdir $log
485                 set refresh_timer [clock seconds]
486             }
487         }
488     }
489
490     # get results of started threads
491     if { $parallel > 0 } {
492         _testgrid_process_jobs $worker
493         # release thread pool
494         if { $nbpooled > 0 } {
495             tpool::cancel $worker [array names job_def]
496         }
497         catch {tpool::resume $worker}
498         tpool::release $worker
499     }
500
501     uplevel dchrono _timer stop
502     set time [lindex [split [uplevel dchrono _timer show] "\n"] 0]
503
504     if { $userbreak } {
505         _log_and_puts log "*********** Stopped by user break ***********"
506         set time "${time} \nNote: the process is not finished, stopped by user break!"
507     }
508
509     ######################################################
510     # output summary logs and exit
511     ######################################################
512
513     _log_summarize $logdir $log $time
514     if { $logdir != "" } {
515         puts "Detailed logs are saved in $logdir"
516     }
517     if { $logdir != "" && $xmlfile != "" } {
518         # XML output file is assumed relative to log dir unless it is absolute
519         if { [ file pathtype $xmlfile] == "relative" } {
520             set xmlfile [file normalize $logdir/$xmlfile]
521         }
522         _log_xml_summary $logdir $xmlfile $log 0
523         puts "XML summary is saved to $xmlfile"
524     }
525     # play sound signal at the end of test
526     if {$signal} {
527         puts "\7\7\7\7"
528     }
529     return
530 }
531
532 # Procedure to regenerate summary log from logs of test cases
533 help testsummarize {
534   Regenerate summary log in the test directory from logs of test cases.
535   This can be necessary if test grids are executed separately (e.g. on
536   different stations) or some grids have been re-executed.
537   Use: testsummarize dir
538 }
539 proc testsummarize {dir} {
540     global _test_case_regexp
541
542     if { ! [file isdirectory $dir] } {
543         error "Error: \"$dir\" is not a directory"
544     }
545
546     # get summary statements from all test cases in one log
547     set log {}
548
549     # to avoid huge listing of logs, first find all subdirectories and iterate
550     # by them, parsing log files in each subdirectory independently 
551     foreach grid [glob -directory $dir -types d -tails */*] {
552         foreach caselog [glob -nocomplain -directory [file join $dir $grid] -types f -tails *.log] {
553             set file [file join $dir $grid $caselog]
554             set nbfound 0
555             set fd [open $file r]
556             while { [gets $fd line] >= 0 } {
557                 if { [regexp $_test_case_regexp $line res grp grd cas status message] } {
558                     if { "[file join $grid $caselog]" != "[file join $grp $grd ${cas}.log]" } { 
559                         puts "Error: $file contains status line for another test case ($line)"
560                     }
561                     lappend log $line
562                     incr nbfound
563                 }
564             }
565             close $fd
566
567             if { $nbfound != 1 } { 
568                 puts "Error: $file contains $nbfound status lines, expected 1"
569             }
570         }
571     }
572
573     _log_summarize $dir $log "Summary regenerated from logs at [clock format [clock seconds]]"
574     return
575 }
576
577 # Procedure to compare results of two runs of test cases
578 help testdiff {
579   Compare results of two executions of tests (CPU times, ...)
580   Use: testdiff dir1 dir2 [groupname [gridname]] [options...]
581   Where dir1 and dir2 are directories containing logs of two test runs.
582   Allowed options are:
583   -save filename: save resulting log in specified file (default name is
584                   <dir1>/diff-<dir2>.log); HTML log is saved with same name
585                   and extension .html
586   -status {same|ok|all}: filter cases for comparing by their status:
587           same - only cases with same status are compared (default)
588           ok   - only cases with OK status in both logs are compared
589           all  - results are compared regardless of status
590   -verbose level: 
591           1 - output only differences 
592           2 - output also list of logs and directories present in one of dirs only
593           3 - (default) output also progress messages 
594   -highlight_percent value: highlight considerable (>value in %) deviations
595                             of CPU and memory (default value is 5%)
596 }
597 proc testdiff {dir1 dir2 args} {
598     if { "$dir1" == "$dir2" } {
599         error "Input directories are the same"
600     }
601
602     ######################################################
603     # check arguments
604     ######################################################
605
606     # treat options
607     set logfile [file join $dir1 "diff-[file tail $dir2].log"]
608     set basename ""
609     set status "same"
610     set verbose 3
611     set highlight_percent 5
612     for {set narg 0} {$narg < [llength $args]} {incr narg} {
613         set arg [lindex $args $narg]
614
615         # log file name
616         if { $arg == "-save" } {
617             incr narg
618             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
619                 set logfile [lindex $args $narg]
620             } else {
621                 error "Error: Option -save must be followed by log file name"
622             } 
623             continue
624         }
625
626         # status filter
627         if { $arg == "-status" } {
628             incr narg
629             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
630                 set status [lindex $args $narg]
631             } else {
632                 set status ""
633             }
634             if { "$status" != "same" && "$status" != "all" && "$status" != "ok" } {
635                 error "Error: Option -status must be followed by one of \"same\", \"all\", or \"ok\""
636             }
637             continue
638         }
639
640         # verbose level
641         if { $arg == "-verbose" } {
642             incr narg
643             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
644                 set verbose [expr [lindex $args $narg]]
645             } else {
646                 error "Error: Option -verbose must be followed by integer verbose level"
647             }
648             continue
649         }
650
651         # highlight_percent
652         if { $arg == "-highlight_percent" } {
653             incr narg
654             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
655                 set highlight_percent [expr [lindex $args $narg]]
656             } else {
657                 error "Error: Option -highlight_percent must be followed by integer value"
658             }
659             continue
660         }
661
662         if { [regexp {^-} $arg] } {
663             error "Error: unsupported option \"$arg\""
664         }
665
666         # non-option arguments form a subdirectory path
667         set basename [file join $basename $arg]
668     }
669
670     # run diff procedure (recursive)
671     _test_diff $dir1 $dir2 $basename $status $verbose log
672
673     # save result to log file
674     if { "$logfile" != "" } {
675         _log_save $logfile [join $log "\n"]
676         _log_html_diff "[file rootname $logfile].html" $log $dir1 $dir2 ${highlight_percent}
677         puts "Log is saved to $logfile (and .html)"
678     }
679
680     return
681 }
682
683 # Procedure to check data file before adding it to repository
684 help testfile {
685   Check data file and prepare it for putting to test data files repository.
686   Use: testfile [filelist]
687
688   Will report if:
689   - data file (non-binary) is in DOS encoding (CR/LF)
690   - same data file (with same or another name) already exists in the repository
691   - another file with the same name already exists 
692   Note that names are assumed to be case-insensitive (for Windows).
693
694   Unless the file is already in the repository, tries to load it, reports
695   the recognized file format, file size, number of faces and edges in the 
696   loaded shape (if any), and makes snapshot (in the temporary directory).
697   Finally it advises whether the file should be put to public section of the 
698   repository.
699 }
700 proc testfile {filelist} {
701     global env
702
703     # check that CSF_TestDataPath is defined
704     if { ! [info exists env(CSF_TestDataPath)] } {
705         error "Environment variable CSF_TestDataPath must be defined!"
706     }
707
708     # build registry of existing data files (name -> path) and (size -> path)
709     puts "Checking available test data files..."
710     foreach dir [_split_path $env(CSF_TestDataPath)] {
711         while {[llength $dir] != 0} {
712             set curr [lindex $dir 0]
713             set dir [lrange $dir 1 end]
714             eval lappend dir [glob -nocomplain -directory $curr -type d *]
715             foreach file [glob -nocomplain -directory $curr -type f *] {
716                 set name [file tail $file]
717                 set name_lower [string tolower $name]
718
719                 # check that the file is not in DOS encoding
720                 if { [_check_dos_encoding $file] } {
721                     puts "Warning: file $file is in DOS encoding; was this intended?"
722                 }
723                 _check_file_format $file
724
725                 # check if file with the same name is present twice or more
726                 if { [info exists names($name_lower)] } {
727                     puts "Error: more than one file with name $name is present in the repository:"
728                     if { [_diff_files $file $names($name_lower)] } {
729                         puts "(files are different by content)"
730                     } else {
731                         puts "(files are same by content)"
732                     }
733                     puts "--> $file"
734                     puts "--> $names($name_lower)"
735                     continue
736                 } 
737                 
738                 # check if file with the same content exists
739                 set size [file size $file]
740                 if { [info exists sizes($size)] } {
741                     foreach other $sizes($size) {
742                         if { ! [_diff_files $file $other] } {
743                             puts "Warning: two files with the same content found:"
744                             puts "--> $file"
745                             puts "--> $other"
746                         }
747                     }
748                 }
749
750                 # add the file to the registry
751                 set names($name_lower) $file
752                 lappend sizes($size) $file
753             }
754         }
755     }
756     if { [llength $filelist] <= 0 } { return }
757
758     # check the new files
759     set has_images f
760     puts "Checking new file(s)..."
761     foreach file $filelist {
762         # check for DOS encoding
763         if { [_check_dos_encoding $file] } {
764             puts "$file: Warning: DOS encoding detected"
765         }
766
767         set name [file tail $file]
768         set name_lower [string tolower $name]
769
770         # check for presence of the file with same name
771         if { [info exists names($name_lower)] } {
772             if { [_diff_files $file $names($name_lower)] } {
773                 puts "$file: Error: name is already used by existing file\n--> $names($name_lower)"
774             } else {
775                 puts "$file: OK: already in the repository \n--> $names($name_lower)"
776                 continue
777             }
778         }
779                 
780         # check if file with the same content exists
781         set size [file size $file]
782         if { [info exists sizes($size)] } {
783             set found f
784             foreach other $sizes($size) {
785                 if { ! [_diff_files $file $other] } {
786                     puts "$file: OK: the same file is already present under name [file tail $other]\n--> $other"
787                     set found t
788                     break
789                 }
790             }
791             if { $found } { continue }
792         }
793
794         # try to read the file
795         set format [_check_file_format $file]
796         if { [catch {uplevel load_data_file $file $format a}] } {
797             puts "$file: Error: Cannot read as $format file"
798             continue
799         }
800
801         # get number of faces and edges
802         set edges 0
803         set faces 0
804         set nbs [uplevel nbshapes a]
805         regexp {EDGE[ \t:]*([0-9]+)} $nbs res edges
806         regexp {FACE[ \t:]*([0-9]+)} $nbs res faces
807
808         # classify; first check file size and number of faces and edges
809         if { $size < 95000 && $faces < 20 && $edges < 100 } {
810             set dir public
811         } else {
812             set dir private
813             # check if one of names of that file corresponds to typical name for 
814             # MDTV bugs or has extension .rle, this should be old model
815             if { [regexp -nocase {.*(cts|ats|pro|buc|ger|fra|usa|uki)[0-9]+.*} $name] ||
816                  [regexp -nocase {[.]rle\y} $name] } {
817                 set dir old
818             }
819         }
820
821         # add stats
822         puts "$file: $format size=[expr $size / 1024] KiB, nbfaces=$faces, nbedges=$edges -> $dir"
823
824         set tmpdir [_get_temp_dir]
825         file mkdir $tmpdir/$dir
826
827         # make snapshot
828         pload AISV
829         uplevel vdisplay a
830         uplevel vfit
831         uplevel vzfit
832         uplevel vdump $tmpdir/$dir/[file rootname [file tail $file]].png
833         set has_images t
834     }
835     if { $has_images } {
836         puts "Snapshots are saved in subdirectory [_get_temp_dir]"
837     }
838 }
839
840 # Procedure to locate data file for test given its name.
841 # The search is performed assuming that the function is called
842 # from the test case script; the search order is:
843 # - subdirectory "data" of the test script (grid) folder
844 # - subdirectories in environment variable CSF_TestDataPath
845 # - subdirectory set by datadir command
846 # If file is not found, raises Tcl error.
847 proc locate_data_file {filename} {
848     global env groupname gridname casename
849
850     # check if the file is located in the subdirectory data of the script dir
851     set scriptfile [info script]
852     if { $scriptfile != "" } {
853         set path [file join [file dirname $scriptfile] data $filename]
854         if { [file exists $path] } {
855             return [file normalize $path]
856         }
857     }
858
859     # check sub-directories in paths indicated by CSF_TestDataPath
860     if { [info exists env(CSF_TestDataPath)] } {
861         foreach dir [_split_path $env(CSF_TestDataPath)] {
862             while {[llength $dir] != 0} { 
863                 set name [lindex $dir 0]
864                 set dir [lrange $dir 1 end]
865                 # skip directories starting with dot
866                 if { [regexp {^[.]} $name] } { continue }
867                 if { [file exists $name/$filename] } {
868                     return [file normalize $name/$filename]
869                 }
870                 eval lappend dir [glob -nocomplain -directory $name -type d *]
871             }
872         }
873     }
874
875     # check current datadir
876     if { [file exists [uplevel datadir]/$filename] } {
877         return [file normalize [uplevel datadir]/$filename]
878     }
879
880     # raise error
881     error [join [list "File $filename could not be found" \
882                       "(should be in paths indicated by CSF_TestDataPath environment variable, " \
883                       "or in subfolder data in the script directory)"] "\n"]
884 }
885
886 # Internal procedure to find test case indicated by group, grid, and test case names;
887 # returns:
888 # - dir: path to the base directory of the tests group
889 # - gridname: actual name of the grid
890 # - casefile: path to the test case script 
891 # if no such test is found, raises error with appropriate message
892 proc _get_test {group grid casename _dir _gridname _casefile} {
893     upvar $_dir dir
894     upvar $_gridname gridname
895     upvar $_casefile casefile
896
897     global env
898  
899     # check that environment variable defining paths to test scripts is defined
900     if { ! [info exists env(CSF_TestScriptsPath)] || 
901          [llength $env(CSF_TestScriptsPath)] <= 0 } {
902         error "Error: Environment variable CSF_TestScriptsPath is not defined"
903     }
904
905     # iterate by all script paths
906     foreach dir [_split_path $env(CSF_TestScriptsPath)] {
907         # protection against empty paths
908         set dir [string trim $dir]
909         if { $dir == "" } { continue }
910
911         # check that directory exists
912         if { ! [file isdirectory $dir] } {
913             puts "Warning: directory $dir listed in CSF_TestScriptsPath does not exist, skipped"
914             continue
915         }
916
917         # check if test group with given name exists in this dir
918         # if not, continue to the next test dir
919         if { ! [file isdirectory $dir/$group] } { continue }
920
921         # check that grid with given name (possibly alias) exists; stop otherwise
922         set gridname $grid
923         if { ! [file isdirectory $dir/$group/$gridname] } {
924             # check if grid is named by alias rather than by actual name
925             if { [file exists $dir/$group/grids.list] } {
926                 set fd [open $dir/$group/grids.list]
927                 while { [gets $fd line] >= 0 } {
928                     if { [regexp "\[ \t\]*\#.*" $line] } { continue }
929                     if { [regexp "^$grid\[ \t\]*\(\[A-Za-z0-9_.-\]+\)\$" $line res gridname] } {
930                         break
931                     }
932                 }
933                 close $fd
934             }
935         }
936         if { ! [file isdirectory $dir/$group/$gridname] } { continue }
937
938         # get actual file name of the script; stop if it cannot be found
939         set casefile $dir/$group/$gridname/$casename
940         if { ! [file exists $casefile] } {
941             # check if this grid is aliased to another one
942             if { [file exists $dir/$group/$gridname/cases.list] } {
943                 set fd [open $dir/$group/$gridname/cases.list]
944                 if { [gets $fd line] >= 0 } {
945                     set casefile [file normalize $dir/$group/$gridname/[string trim $line]/$casename]
946                 }
947                 close $fd
948             }
949         }
950         if { [file exists $casefile] } { 
951             # normal return
952             return 
953         }
954     }
955
956     # coming here means specified test is not found; report error
957     error [join [list "Error: test case $group / $grid / $casename is not found in paths listed in variable" \
958                       "CSF_TestScriptsPath (current value is \"$env(CSF_TestScriptsPath)\")"] "\n"]
959 }
960
961 # Internal procedure to run test case indicated by base directory, 
962 # grid and grid names, and test case file path.
963 # The log can be obtained by command "dlog get".
964 proc _run_test {scriptsdir group gridname casefile echo} {
965     global env
966
967     # start timer
968     uplevel dchrono _timer reset
969     uplevel dchrono _timer start
970     catch {uplevel meminfo h} membase
971
972     # enable commands logging; switch to old-style mode if dlog command is not present
973     set dlog_exists 1
974     if { [catch {dlog reset}] } {
975         set dlog_exists 0
976     } elseif { $echo } {
977         decho on
978     } else {
979         dlog reset
980         dlog on
981         rename puts puts-saved
982         proc puts args { 
983             global _tests_verbose
984
985             # log only output to stdout and stderr, not to file!
986             if {[llength $args] > 1} {
987                 set optarg [lindex $args end-1]
988                 if { $optarg == "stdout" || $optarg == "stderr" || $optarg == "-newline" } {
989                     dlog add [lindex $args end]
990                 } else {
991                     eval puts-saved $args
992                 }
993             } else {
994                 dlog add [lindex $args end]
995             }
996         }
997     }
998
999     # evaluate test case 
1000     set tmp_imagedir 0
1001     if [catch {
1002         # set variables identifying test case
1003         uplevel set casename [file tail $casefile]
1004         uplevel set groupname $group
1005         uplevel set gridname $gridname
1006         uplevel set dirname  $scriptsdir
1007
1008         # set path for saving of log and images (if not yet set) to temp dir
1009         if { ! [uplevel info exists imagedir] } {
1010             uplevel set test_image \$casename
1011
1012             # create subdirectory in temp named after group and grid with timestamp
1013             set rootlogdir [_get_temp_dir]
1014         
1015             set imagedir "${group}-${gridname}-${::casename}-[clock format [clock seconds] -format {%Y-%m-%dT%Hh%Mm%Ss}]"
1016             set imagedir [file normalize ${rootlogdir}/$imagedir]
1017
1018             if { [catch {file mkdir $imagedir}] || ! [file writable $imagedir] ||
1019                  ! [catch {glob -directory $imagedir *}] } {
1020                  # puts "Warning: Cannot create directory \"$imagedir\", or it is not empty; \"${rootlogdir}\" is used"
1021                 set imagedir $rootlogdir
1022             }
1023
1024             uplevel set imagedir \"$imagedir\"
1025             set tmp_imagedir 1
1026         }
1027
1028         # execute test scripts 
1029         if { [file exists $scriptsdir/$group/begin] } {
1030             puts "Executing $scriptsdir/$group/begin..."; flush stdout
1031             uplevel source $scriptsdir/$group/begin
1032         }
1033         if { [file exists $scriptsdir/$group/$gridname/begin] } {
1034             puts "Executing $scriptsdir/$group/$gridname/begin..."; flush stdout
1035             uplevel source $scriptsdir/$group/$gridname/begin
1036         }
1037
1038         puts "Executing $casefile..."; flush stdout
1039         uplevel source $casefile
1040
1041         if { [file exists $scriptsdir/$group/$gridname/end] } {
1042             puts "Executing $scriptsdir/$group/$gridname/end..."; flush stdout
1043             uplevel source $scriptsdir/$group/$gridname/end
1044         }
1045         if { [file exists $scriptsdir/$group/end] } {
1046             puts "Executing $scriptsdir/$group/end..."; flush stdout
1047             uplevel source $scriptsdir/$group/end
1048         }
1049     } res] {
1050         puts "Tcl Exception: $res"
1051     }
1052
1053     # stop logging
1054     if { $dlog_exists } {
1055         if { $echo } {
1056             decho off
1057         } else {
1058             rename puts {}
1059             rename puts-saved puts
1060             dlog off
1061         }
1062     }
1063
1064     # stop cpulimit killer if armed by the test
1065     cpulimit
1066
1067     # add memory and timing info
1068     set stats ""
1069     if { ! [catch {uplevel meminfo h} memuse] } {
1070         append stats "MEMORY DELTA: [expr ($memuse - $membase) / 1024] KiB\n"
1071     }
1072     uplevel dchrono _timer stop
1073     set time [uplevel dchrono _timer show]
1074     if { [regexp -nocase {CPU user time:[ \t]*([0-9.e-]+)} $time res cpu_usr] } {
1075         append stats "TOTAL CPU TIME: $cpu_usr sec\n"
1076     }
1077     if { $dlog_exists && ! $echo } {
1078         dlog add $stats
1079     } else {
1080         puts $stats
1081     }
1082
1083     # unset global vars
1084     uplevel unset casename groupname gridname dirname
1085     if { $tmp_imagedir } { uplevel unset imagedir test_image }
1086 }
1087
1088 # Internal procedure to check log of test execution and decide if it passed or failed
1089 proc _check_log {dir group gridname casename errors log {_summary {}} {_html_log {}}} {
1090     global env
1091     if { $_summary != "" } { upvar $_summary summary }
1092     if { $_html_log != "" } { upvar $_html_log html_log }
1093     set summary {}
1094     set html_log {}
1095     set errors_log {}
1096
1097     if [catch {
1098
1099         # load definition of 'bad words' indicating test failure
1100         # note that rules are loaded in the order of decreasing priority (grid - group - common),
1101         # thus grid rules will override group ones
1102         set badwords {}
1103         foreach rulesfile [list $dir/$group/$gridname/parse.rules $dir/$group/parse.rules $dir/parse.rules] {
1104             if [catch {set fd [open $rulesfile r]}] { continue }
1105             while { [gets $fd line] >= 0 } {
1106                 # skip comments and empty lines
1107                 if { [regexp "\[ \t\]*\#.*" $line] } { continue }
1108                 if { [string trim $line] == "" } { continue }
1109                 # extract regexp
1110                 if { ! [regexp {^([^/]*)/([^/]*)/(.*)$} $line res status rexp comment] } { 
1111                     puts "Warning: cannot recognize parsing rule \"$line\" in file $rulesfile"
1112                     continue 
1113                 }
1114                 set status [string trim $status]
1115                 if { $comment != "" } { append status " ([string trim $comment])" }
1116                 set rexp [regsub -all {\\b} $rexp {\\y}] ;# convert regexp from Perl to Tcl style
1117                 lappend badwords [list $status $rexp]
1118             }
1119             close $fd
1120         }
1121         if { [llength $badwords] <= 0 } { 
1122             puts "Warning: no definition of error indicators found (check files parse.rules)" 
1123         }
1124
1125         # analyse log line-by-line
1126         set todos {} ;# TODO statements
1127         set requs {} ;# REQUIRED statements
1128         set todo_incomplete -1
1129         set status ""
1130         foreach line [split $log "\n"] {
1131             # check if line defines specific treatment of some messages
1132             if [regexp -nocase {^[ \s]*TODO ([^:]*):(.*)$} $line res platforms pattern] {
1133                 if { ! [regexp -nocase {\mAll\M} $platforms] && 
1134                      ! [regexp -nocase "\\m$env(os_type)\\M" $platforms] } {
1135                     lappend html_log [_html_highlight IGNORE $line]
1136                     continue ;# TODO statement is for another platform
1137                 }
1138
1139                 # record TODOs that mark unstable cases
1140                 if { [regexp {[\?]} $platforms] } {
1141                     set todos_unstable([llength $todos]) 1
1142                 }
1143
1144                 # convert legacy regexps from Perl to Tcl style
1145                 set pattern [regsub -all {\\b} [string trim $pattern] {\\y}]
1146
1147                 # special case: TODO TEST INCOMPLETE
1148                 if { [string trim $pattern] == "TEST INCOMPLETE" } {
1149                     set todo_incomplete [llength $todos]
1150                 }
1151
1152                 lappend todos [list $pattern [llength $html_log] $line]
1153                 lappend html_log [_html_highlight BAD $line]
1154                 continue
1155             }
1156             if [regexp -nocase {^[ \s]*REQUIRED ([^:]*):[ \s]*(.*)$} $line res platforms pattern] {
1157                 if { ! [regexp -nocase {\mAll\M} $platforms] && 
1158                      ! [regexp -nocase "\\m$env(os_type)\\M" $platforms] } {
1159                     lappend html_log [_html_highlight IGNORE $line]
1160                     continue ;# REQUIRED statement is for another platform
1161                 }
1162                 lappend requs [list $pattern [llength $html_log] $line]
1163                 lappend html_log [_html_highlight OK $line]
1164                 continue
1165             }
1166
1167             # check for presence of required messages 
1168             set ismarked 0
1169             for {set i 0} {$i < [llength $requs]} {incr i} {
1170                 set pattern [lindex $requs $i 0]
1171                 if { [regexp $pattern $line] } {
1172                     incr required_count($i)
1173                     lappend html_log [_html_highlight OK $line]
1174                     set ismarked 1
1175                     continue
1176                 }
1177             }
1178             if { $ismarked } {
1179                 continue
1180             }
1181
1182             # check for presence of messages indicating test result
1183             foreach bw $badwords {
1184                 if { [regexp [lindex $bw 1] $line] } { 
1185                     # check if this is known bad case
1186                     set is_known 0
1187                     for {set i 0} {$i < [llength $todos]} {incr i} {
1188                         set pattern [lindex $todos $i 0]
1189                         if { [regexp $pattern $line] } {
1190                             set is_known 1
1191                             incr todo_count($i)
1192                             lappend html_log [_html_highlight BAD $line]
1193                             break
1194                         }
1195                     }
1196
1197                     # if it is not in todo, define status
1198                     if { ! $is_known } {
1199                         set stat [lindex $bw 0 0]
1200                         if {$errors} {
1201                             lappend errors_log $line
1202                         }
1203                         lappend html_log [_html_highlight $stat $line]
1204                         if { $status == "" && $stat != "OK" && ! [regexp -nocase {^IGNOR} $stat] } {
1205                             set status [lindex $bw 0]
1206                         }
1207                     }
1208                     set ismarked 1
1209                     break
1210                 }
1211             }
1212             if { ! $ismarked } { 
1213                lappend html_log $line
1214             }
1215         }
1216
1217         # check for presence of TEST COMPLETED statement
1218         if { $status == "" && ! [regexp {TEST COMPLETED} $log] } {
1219             # check whether absence of TEST COMPLETED is known problem
1220             if { $todo_incomplete >= 0 } {
1221                 incr todo_count($todo_incomplete)
1222             } else {
1223                 set status "FAILED (no final message is found)"
1224             }
1225         }
1226
1227         # report test as failed if it doesn't contain required pattern
1228         if { $status == "" } {
1229             for {set i 0} {$i < [llength $requs]} {incr i} {
1230                 if { ! [info exists required_count($i)] } {
1231                     set linenum [lindex $requs $i 1]
1232                     set html_log [lreplace $html_log $linenum $linenum [_html_highlight FAILED [lindex $requs $i 2]]]
1233                     set status "FAILED (REQUIRED statement no. [expr $i + 1] is not found)"
1234                 }
1235             }
1236         }
1237
1238         # check declared bad cases and diagnose possible improvement 
1239         # (bad case declared but not detected).
1240         # Note that absence of the problem marked by TODO with question mark
1241         # (unstable) is not reported as improvement.
1242         if { $status == "" } {
1243             for {set i 0} {$i < [llength $todos]} {incr i} {
1244                 if { ! [info exists todos_unstable($i)] &&
1245                      (! [info exists todo_count($i)] || $todo_count($i) <= 0) } {
1246                     set linenum [lindex $todos $i 1]
1247                     set html_log [lreplace $html_log $linenum $linenum [_html_highlight IMPROVEMENT [lindex $todos $i 2]]]
1248                     set status "IMPROVEMENT (expected problem TODO no. [expr $i + 1] is not detected)"
1249                     break;
1250                 }
1251             }
1252         }
1253
1254         # report test as known bad if at least one of expected problems is found
1255         if { $status == "" && [llength [array names todo_count]] > 0 } {
1256             set status "BAD (known problem)"
1257         }
1258
1259         # report normal OK
1260         if { $status == "" } {set status "OK" }
1261
1262     } res] {
1263         set status "FAILED ($res)"
1264     }
1265
1266     # put final message
1267     _log_and_puts summary "CASE $group $gridname $casename: $status"
1268     set summary [join $summary "\n"]
1269     if {$errors} {
1270         foreach error $errors_log {
1271             _log_and_puts summary "  $error"
1272         }
1273     }
1274     set html_log "[_html_highlight [lindex $status 0] $summary]\n[join $html_log \n]"
1275 }
1276
1277 # Auxiliary procedure putting message to both cout and log variable (list)
1278 proc _log_and_puts {logvar message} {
1279     if { $logvar != "" } { 
1280         upvar $logvar log
1281         lappend log $message
1282     }
1283     puts $message
1284 }
1285
1286 # Auxiliary procedure to log result on single test case
1287 proc _log_test_case {output logdir dir group grid casename logvar} {
1288     upvar $logvar log
1289     set show_errors 0
1290     # check result and make HTML log
1291     _check_log $dir $group $grid $casename $show_errors $output summary html_log
1292     lappend log $summary
1293
1294     # save log to file
1295     if { $logdir != "" } {
1296         _log_html $logdir/$group/$grid/$casename.html $html_log "Test $group $grid $casename"
1297         _log_save $logdir/$group/$grid/$casename.log "$output\n$summary" "Test $group $grid $casename"
1298     }
1299 }
1300
1301 # Auxiliary procedure to save log to file
1302 proc _log_save {file log {title {}}} {
1303     # create missing directories as needed
1304     catch {file mkdir [file dirname $file]}
1305
1306     # try to open a file
1307     if [catch {set fd [open $file w]} res] {
1308         error "Error saving log file $file: $res"
1309     }
1310     
1311     # dump log and close
1312     puts $fd "$title\n"
1313     puts $fd $log
1314     close $fd
1315     return
1316 }
1317
1318 # Auxiliary procedure to make a (relative if possible) URL to a file for 
1319 # inclusion a reference in HTML log
1320 proc _make_url {htmldir file} {
1321     set htmlpath [file split [file normalize $htmldir]]
1322     set filepath [file split [file normalize $file]]
1323     for {set i 0} {$i < [llength $htmlpath]} {incr i} {
1324         if { "[lindex $htmlpath $i]" != "[lindex $filepath $i]" } {
1325             if { $i == 0 } { break }
1326             return "[string repeat "../" [expr [llength $htmlpath] - $i - 1]][eval file join [lrange $filepath $i end]]"
1327         }
1328     }
1329
1330     # if relative path could not be made, return full file URL
1331     return "file://[file normalize $file]"
1332 }
1333
1334 # Auxiliary procedure to save log to file
1335 proc _log_html {file log {title {}}} {
1336     # create missing directories as needed
1337     catch {file mkdir [file dirname $file]}
1338
1339     # try to open a file
1340     if [catch {set fd [open $file w]} res] {
1341         error "Error saving log file $file: $res"
1342     }
1343     
1344     # print header
1345     puts $fd "<html><head><title>$title</title></head><body><h1>$title</h1>"
1346
1347     # add images if present; these should have either PNG, GIF, or JPG extension,
1348     # and start with name of the test script, with optional suffix separated
1349     # by underscore or dash
1350     set imgbasename [file rootname [file tail $file]]
1351     foreach img [lsort [glob -nocomplain -directory [file dirname $file] -tails \
1352                              ${imgbasename}.gif   ${imgbasename}.png   ${imgbasename}.jpg \
1353                              ${imgbasename}_*.gif ${imgbasename}_*.png ${imgbasename}_*.jpg \
1354                              ${imgbasename}-*.gif ${imgbasename}-*.png ${imgbasename}-*.jpg]] {
1355         puts $fd "<p>[file tail $img]<br><img src=\"$img\"/><p>"
1356     }
1357
1358     # print log body, trying to add HTML links to script files on lines like
1359     # "Executing <filename>..."
1360     puts $fd "<pre>"
1361     foreach line [split $log "\n"] {
1362         if { [regexp {Executing[ \t]+([a-zA-Z0-9._/:-]+[^.])} $line res script] &&
1363              [file exists $script] } {
1364             set line [regsub $script $line "<a href=\"[_make_url $file $script]\">$script</a>"]
1365         }
1366         puts $fd $line
1367     }
1368     puts $fd "</pre></body></html>"
1369
1370     close $fd
1371     return
1372 }
1373
1374 # Auxiliary method to make text with HTML highlighting according to status
1375 proc _html_color {status} {
1376     # choose a color for the cell according to result
1377     if { $status == "OK" } { 
1378         return lightgreen
1379     } elseif { [regexp -nocase {^FAIL} $status] } { 
1380         return red
1381     } elseif { [regexp -nocase {^BAD} $status] } { 
1382         return yellow
1383     } elseif { [regexp -nocase {^IMP} $status] } { 
1384         return orange
1385     } elseif { [regexp -nocase {^SKIP} $status] } { 
1386         return gray
1387     } elseif { [regexp -nocase {^IGNOR} $status] } { 
1388         return gray
1389     } else {
1390         puts "Warning: no color defined for status $status, using red as if FAILED"
1391         return red
1392     }
1393 }
1394
1395 # Format text line in HTML to be colored according to the status
1396 proc _html_highlight {status line} {
1397     return "<table><tr><td bgcolor=\"[_html_color $status]\">$line</td></tr></table>"
1398 }
1399
1400 # Internal procedure to generate HTML page presenting log of the tests
1401 # execution in tabular form, with links to reports on individual cases
1402 proc _log_html_summary {logdir log totals regressions improvements total_time} {
1403     global _test_case_regexp
1404
1405     # create missing directories as needed
1406     file mkdir $logdir
1407
1408     # try to open a file and start HTML
1409     if [catch {set fd [open $logdir/summary.html w]} res] {
1410         error "Error creating log file: $res"
1411     }
1412
1413     # write HRML header, including command to refresh log if still in progress
1414     puts $fd "<html><head>"
1415     puts $fd "<title>Tests summary</title>"
1416     if { $total_time == "" } {
1417         puts $fd "<meta http-equiv=\"refresh\" content=\"10\">"
1418     }
1419     puts $fd "<meta http-equiv=\"pragma\" content=\"NO-CACHE\">"
1420     puts $fd "</head><body>"
1421
1422     # put summary
1423     set legend(OK)          "Test passed OK"
1424     set legend(FAILED)      "Test failed (regression)"
1425     set legend(BAD)         "Known problem"
1426     set legend(IMPROVEMENT) "Possible improvement (expected problem not detected)"
1427     set legend(SKIPPED)     "Test skipped due to lack of data file"
1428     puts $fd "<h1>Summary</h1><table>"
1429     foreach nbstat $totals {
1430         set status [lindex $nbstat 1]
1431         if { [info exists legend($status)] } { 
1432             set comment $legend($status) 
1433         } else {
1434             set comment "User-defined status"
1435         }
1436         puts $fd "<tr><td align=\"right\">[lindex $nbstat 0]</td><td bgcolor=\"[_html_color $status]\">$status</td><td>$comment</td></tr>"
1437     }
1438     puts $fd "</table>"
1439
1440     # time stamp and elapsed time info
1441     if { $total_time != "" } { 
1442         puts $fd "<p>Generated on [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S}] on [info hostname]\n<p>"
1443         puts $fd [join [split $total_time "\n"] "<p>"]
1444     } else {
1445         puts $fd "<p>NOTE: This is intermediate summary; the tests are still running! This page will refresh automatically until tests are finished."
1446     }
1447    
1448     # print regressions and improvements
1449     foreach featured [list $regressions $improvements] {
1450         if { [llength $featured] <= 1 } { continue }
1451         set status [string trim [lindex $featured 0] { :}]
1452         puts $fd "<h2>$status</h2>"
1453         puts $fd "<table>"
1454         set groupgrid ""
1455         foreach test [lrange $featured 1 end] {
1456             if { ! [regexp {^(.*)\s+([\w.]+)$} $test res gg name] } {
1457                 set gg UNKNOWN
1458                 set name "Error building short list; check details"
1459             }
1460             if { $gg != $groupgrid } {
1461                 if { $groupgrid != "" } { puts $fd "</tr>" }
1462                 set groupgrid $gg
1463                 puts $fd "<tr><td>$gg</td>"
1464             }
1465             puts $fd "<td bgcolor=\"[_html_color $status]\"><a href=\"[regsub -all { } $gg /]/${name}.html\">$name</a></td>"
1466         }
1467         if { $groupgrid != "" } { puts $fd "</tr>" }
1468         puts $fd "</table>"
1469     }
1470
1471     # put detailed log with TOC
1472     puts $fd "<hr><h1>Details</h1>"
1473     puts $fd "<div style=\"float:right; padding: 10px; border-style: solid; border-color: blue; border-width: 2px;\">"
1474
1475     # process log line-by-line
1476     set group {}
1477     set letter {}
1478     set body {}
1479     foreach line [lsort -dictionary $log] {
1480         # check that the line is case report in the form "CASE group grid name: result (explanation)"
1481         if { ! [regexp $_test_case_regexp $line res grp grd casename result message] } {
1482             continue
1483         }
1484
1485         # start new group
1486         if { $grp != $group } {
1487             if { $letter != "" } { lappend body "</tr></table>" }
1488             set letter {}
1489             set group $grp
1490             set grid {}
1491             puts $fd "<a href=\"#$group\">$group</a><br>"
1492             lappend body "<h2><a name=\"$group\">Group $group</a></h2>"
1493         }
1494
1495         # start new grid
1496         if { $grd != $grid } {
1497             if { $letter != "" } { lappend body "</tr></table>" }
1498             set letter {}
1499             set grid $grd
1500             puts $fd "&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"#$group-$grid\">$grid</a><br>"
1501             lappend body "<h2><a name=\"$group-$grid\">Grid $group $grid</a></h2>"
1502         }
1503
1504         # check if test case name is <letter><digit>; 
1505         # if not, set alnum to period "." to recognize non-standard test name
1506         if { ! [regexp {\A([A-Za-z]{1,2})([0-9]{1,2})\Z} $casename res alnum number] &&
1507              ! [regexp {\A([A-Za-z0-9]+)_([0-9]+)\Z} $casename res alnum number] } {
1508             set alnum $casename
1509         }
1510
1511         # start new row when letter changes or for non-standard names
1512         if { $alnum != $letter || $alnum == "." } {
1513             if { $letter != "" } { 
1514                 lappend body "</tr><tr>" 
1515             } else {
1516                 lappend body "<table><tr>"
1517             }
1518             set letter $alnum
1519         }    
1520
1521         lappend body "<td bgcolor=\"[_html_color $result]\"><a href=\"$group/$grid/${casename}.html\">$casename</a></td>"
1522     }
1523     puts $fd "</div>\n[join $body "\n"]</tr></table>"
1524
1525     # add remaining lines of log as plain text
1526     puts $fd "<h2>Plain text messages</h2>\n<pre>"
1527     foreach line $log {
1528         if { ! [regexp $_test_case_regexp $line] } {
1529             puts $fd "$line"
1530         }
1531     }
1532     puts $fd "</pre>"
1533
1534     # close file and exit
1535     puts $fd "</body>"
1536     close $fd
1537     return
1538 }
1539
1540 # Procedure to dump summary logs of tests
1541 proc _log_summarize {logdir log {total_time {}}} {
1542
1543     # sort log records alphabetically to have the same behavior on Linux and Windows 
1544     # (also needed if tests are run in parallel)
1545     set loglist [lsort -dictionary $log]
1546
1547     # classify test cases by status
1548     foreach line $loglist {
1549         if { [regexp {^CASE ([^:]*): ([[:alnum:]]+).*$} $line res caseid status] } {
1550             lappend stat($status) $caseid
1551         }
1552     }
1553     set totals {}
1554     set improvements {Improvements:}
1555     set regressions {Failed:}
1556     if { [info exists stat] } {
1557         foreach status [lsort [array names stat]] {
1558             lappend totals [list [llength $stat($status)] $status]
1559
1560             # separately count improvements (status starting with IMP) and regressions (all except IMP, OK, BAD, and SKIP)
1561             if { [regexp -nocase {^IMP} $status] } {
1562                 eval lappend improvements $stat($status)
1563             } elseif { $status != "OK" && ! [regexp -nocase {^BAD} $status] && ! [regexp -nocase {^SKIP} $status] } {
1564                 eval lappend regressions $stat($status)
1565             }
1566         }
1567     }
1568
1569     # if time is specified, add totals
1570     if { $total_time != "" } {
1571         if { [llength $improvements] > 1 } {
1572             _log_and_puts log [join $improvements "\n  "]
1573         }
1574         if { [llength $regressions] > 1 } {
1575             _log_and_puts log [join $regressions "\n  "]
1576         }
1577         if { [llength $improvements] == 1 && [llength $regressions] == 1 } {
1578             _log_and_puts log "No regressions"
1579         }
1580         _log_and_puts log "Total cases: [join $totals {, }]"
1581         _log_and_puts log $total_time
1582     }
1583
1584     # save log to files
1585     if { $logdir != "" } {
1586         _log_html_summary $logdir $log $totals $regressions $improvements $total_time
1587         _log_save $logdir/tests.log [join $log "\n"] "Tests summary"
1588     }
1589
1590     return
1591 }
1592
1593 # Internal procedure to generate XML log in JUnit style, for further
1594 # consumption by Jenkins or similar systems.
1595 #
1596 # The output is intended to conform to XML schema supported by Jenkins found at
1597 # https://svn.jenkins-ci.org/trunk/hudson/dtkit/dtkit-format/dtkit-junit-model/src/main/resources/com/thalesgroup/dtkit/junit/model/xsd/junit-4.xsd
1598 #
1599 # The mapping of the fields is inspired by annotated schema of Apache Ant JUnit XML format found at
1600 # http://windyroad.org/dl/Open%20Source/JUnit.xsd
1601 proc _log_xml_summary {logdir filename log include_cout} {
1602     global _test_case_regexp
1603
1604     catch {file mkdir [file dirname $filename]}
1605
1606     # try to open a file and start XML
1607     if [catch {set fd [open $filename w]} res] {
1608         error "Error creating XML summary file $filename: $res"
1609     }
1610     puts $fd "<?xml version='1.0' encoding='utf-8'?>"
1611     puts $fd "<testsuites>"
1612
1613     # prototype for command to generate test suite tag
1614     set time_and_host "timestamp=\"[clock format [clock seconds] -format {%Y-%m-%dT%H:%M:%S}]\" hostname=\"[info hostname]\""
1615     set cmd_testsuite {puts $fd "<testsuite name=\"$group $grid\" tests=\"$nbtests\" failures=\"$nbfail\" errors=\"$nberr\" time=\"$time\" skipped=\"$nbskip\" $time_and_host>\n$testcases\n</testsuite>\n"}
1616
1617     # sort log and process it line-by-line
1618     set group {}
1619     foreach line [lsort -dictionary $log] {
1620         # check that the line is case report in the form "CASE group grid name: result (explanation)"
1621         if { ! [regexp $_test_case_regexp $line res grp grd casename result message] } {
1622             continue
1623         }
1624         set message [string trim $message " \t\r\n()"]
1625
1626         # start new testsuite for each grid
1627         if { $grp != $group || $grd != $grid } {
1628
1629             # write previous test suite
1630             if [info exists testcases] { eval $cmd_testsuite }
1631
1632             set testcases {}
1633             set nbtests 0
1634             set nberr 0
1635             set nbfail 0
1636             set nbskip 0
1637             set time 0.
1638
1639             set group $grp
1640             set grid $grd
1641         }
1642
1643         incr nbtests
1644  
1645         # parse test log and get its CPU time
1646         set testout {}
1647         set add_cpu {}
1648         if { [catch {set fdlog [open $logdir/$group/$grid/${casename}.log r]} ret] } { 
1649             puts "Error: cannot open $logdir/$group/$grid/${casename}.log: $ret"
1650         } else {
1651             while { [gets $fdlog logline] >= 0 } {
1652                 if { $include_cout } {
1653                     append testout "$logline\n"
1654                 }
1655                 if [regexp -nocase {TOTAL CPU TIME:\s*([\d.]+)\s*sec} $logline res cpu] {
1656                     set add_cpu " time=\"$cpu\""
1657                     set time [expr $time + $cpu]
1658                 }
1659             }
1660             close $fdlog
1661         }
1662         if { ! $include_cout } {
1663             set testout "$line\n"
1664         }
1665
1666         # record test case with its output and status
1667         # Mapping is: SKIPPED, BAD, and OK to OK, all other to failure
1668         append testcases "\n  <testcase name=\"$casename\"$add_cpu status=\"$result\">\n"
1669         append testcases "\n    <system-out>\n$testout    </system-out>"
1670         if { $result != "OK" } {
1671             if { [regexp -nocase {^SKIP} $result] } {
1672                 incr nberr
1673                 append testcases "\n    <error name=\"$result\" message=\"$message\"/>"
1674             } elseif { [regexp -nocase {^BAD} $result] } {
1675                 incr nbskip
1676                 append testcases "\n    <skipped>$message</skipped>"
1677             } else {
1678                 incr nbfail
1679                 append testcases "\n    <failure name=\"$result\" message=\"$message\"/>"
1680             }
1681         }
1682         append testcases "\n  </testcase>"
1683     }
1684
1685     # write last test suite
1686     if [info exists testcases] { eval $cmd_testsuite }
1687
1688     # the end
1689     puts $fd "</testsuites>"
1690     close $fd
1691     return
1692 }
1693
1694 # define custom platform name 
1695 proc _tests_platform_def {} {
1696     global env tcl_platform
1697
1698     if [info exists env(os_type)] { return }
1699     set env(os_type) $tcl_platform(platform)
1700     if { $tcl_platform(os) == "Linux" } {
1701         set env(os_type) Linux
1702     }
1703     if { $tcl_platform(os) == "Darwin" } {
1704         set env(os_type) MacOS
1705     } 
1706 }
1707 _tests_platform_def
1708
1709 # Auxiliary procedure to split path specification (usually defined by
1710 # environment variable) into list of directories or files
1711 proc _split_path {pathspec} {
1712     global tcl_platform
1713
1714     # first replace all \ (which might occur on Windows) by /  
1715     regsub -all "\\\\" $pathspec "/" pathspec
1716
1717     # split path by platform-specific separator
1718     return [split $pathspec [_path_separator]]
1719 }
1720
1721 # Auxiliary procedure to define platform-specific separator for directories in
1722 # path specification
1723 proc _path_separator {} {
1724     global tcl_platform
1725
1726     # split path by platform-specific separator
1727     if { $tcl_platform(platform) == "windows" } {
1728         return ";"
1729     } else {
1730         return ":"
1731     }
1732 }
1733
1734 # Procedure to make a diff and common of two lists
1735 proc _list_diff {list1 list2 _in1 _in2 _common} {
1736     upvar $_in1 in1
1737     upvar $_in2 in2
1738     upvar $_common common
1739
1740     set in1 {}
1741     set in2 {}
1742     set common {}
1743     foreach item $list1 {
1744         if { [lsearch -exact $list2 $item] >= 0 } {
1745             lappend common $item
1746         } else {
1747             lappend in1 $item
1748         }
1749     }
1750     foreach item $list2 {
1751         if { [lsearch -exact $common $item] < 0 } {
1752             lappend in2 $item
1753         }
1754     }
1755     return
1756 }
1757
1758 # procedure to load a file to Tcl string
1759 proc _read_file {filename} {
1760     set fd [open $filename r]
1761     set result [read -nonewline $fd]
1762     close $fd
1763     return $result
1764 }
1765
1766 # procedure to construct name for the mage diff file
1767 proc _diff_img_name {dir1 dir2 casepath imgfile} {
1768     return [file join $dir1 $casepath "diff-[file tail $dir2]-$imgfile"]
1769 }
1770
1771 # auxiliary procedure to produce string comparing two values
1772 proc _diff_show_ratio {value1 value2} {
1773     return "$value1 / $value2 \[[format "%+5.2f%%" [expr 100 * ($value1 - $value2) / double($value2)]]\]"
1774 }
1775
1776 # Procedure to compare results of two runs of test cases
1777 proc _test_diff {dir1 dir2 basename status verbose _logvar {_statvar ""}} {
1778     upvar $_logvar log
1779
1780     # make sure to load diffimage command
1781     uplevel pload VISUALIZATION
1782
1783     # prepare variable (array) for collecting statistics
1784     if { "$_statvar" != "" } {
1785         upvar $_statvar stat
1786     } else {
1787         set stat(cpu1) 0
1788         set stat(cpu2) 0
1789         set stat(mem1) 0
1790         set stat(mem2) 0
1791         set log {}
1792     }
1793
1794     # first check subdirectories
1795     set path1 [file join $dir1 $basename]
1796     set path2 [file join $dir2 $basename]
1797     set list1 [glob -directory $path1 -types d -tails -nocomplain *]
1798     set list2 [glob -directory $path2 -types d -tails -nocomplain *]
1799     if { [llength $list1] >0 || [llength $list2] > 0 } {
1800         _list_diff $list1 $list2 in1 in2 common
1801         if { "$verbose" > 1 } {
1802             if { [llength $in1] > 0 } { _log_and_puts log "Only in $path1: $in1" }
1803             if { [llength $in2] > 0 } { _log_and_puts log "Only in $path2: $in2" }
1804         }
1805         foreach subdir $common {
1806             if { "$verbose" > 2 } {
1807                 _log_and_puts log "Checking [file join $basename $subdir]"
1808             }
1809             _test_diff $dir1 $dir2 [file join $basename $subdir] $status $verbose log stat
1810         }
1811     } else {
1812         # check log files (only if directory has no subdirs)
1813         set list1 [glob -directory $path1 -types f -tails -nocomplain *.log]
1814         set list2 [glob -directory $path2 -types f -tails -nocomplain *.log]
1815         _list_diff $list1 $list2 in1 in2 common
1816         if { "$verbose" > 1 } {
1817             if { [llength $in1] > 0 } { _log_and_puts log "Only in $path1: $in1" }
1818             if { [llength $in2] > 0 } { _log_and_puts log "Only in $path2: $in2" }
1819         }
1820         set gcpu1 0
1821         set gcpu2 0
1822         set gmem1 0
1823         set gmem2 0
1824         foreach logfile $common {
1825             # load two logs
1826             set log1 [_read_file [file join $dir1 $basename $logfile]]
1827             set log2 [_read_file [file join $dir2 $basename $logfile]]
1828             set casename [file rootname $logfile]
1829
1830             # check execution statuses
1831             set status1 UNDEFINED
1832             set status2 UNDEFINED
1833             if { ! [regexp {CASE [^:]*:\s*([\w]+)} $log1 res1 status1] ||
1834                  ! [regexp {CASE [^:]*:\s*([\w]+)} $log2 res2 status2] ||
1835                  "$status1" != "$status2" } {
1836                 _log_and_puts log "STATUS [split $basename /] $casename: $status1 / $status2"
1837
1838                 # if test statuses are different, further comparison makes 
1839                 # no sense unless explicitly requested
1840                 if { "$status" != "all" } {
1841                     continue
1842                 }
1843             }
1844             if { "$status" == "ok" && "$status1" != "OK" } { 
1845                 continue
1846             }
1847
1848             # check CPU times
1849             set cpu1 UNDEFINED
1850             set cpu2 UNDEFINED
1851             if { [regexp {TOTAL CPU TIME:\s*([\d.]+)} $log1 res1 cpu1] &&
1852                  [regexp {TOTAL CPU TIME:\s*([\d.]+)} $log2 res1 cpu2] } {
1853                 set stat(cpu1) [expr $stat(cpu1) + $cpu1]
1854                 set stat(cpu2) [expr $stat(cpu2) + $cpu2]
1855                 set gcpu1 [expr $gcpu1 + $cpu1]
1856                 set gcpu2 [expr $gcpu2 + $cpu2]
1857
1858                 # compare CPU times with 10% precision (but not less 0.5 sec)
1859                 if { [expr abs ($cpu1 - $cpu2) > 0.5 + 0.05 * abs ($cpu1 + $cpu2)] } {
1860                     _log_and_puts log "CPU [split $basename /] $casename: [_diff_show_ratio $cpu1 $cpu2]"
1861                 }
1862             }
1863
1864             # check memory delta
1865             set mem1 UNDEFINED
1866             set mem2 UNDEFINED
1867             if { [regexp {MEMORY DELTA:\s*([\d.]+)} $log1 res1 mem1] &&
1868                  [regexp {MEMORY DELTA:\s*([\d.]+)} $log2 res1 mem2] } {
1869                 set stat(mem1) [expr $stat(mem1) + $mem1]
1870                 set stat(mem2) [expr $stat(mem2) + $mem2]
1871                 set gmem1 [expr $gmem1 + $mem1]
1872                 set gmem2 [expr $gmem2 + $mem2]
1873
1874                 # compare memory usage with 10% precision (but not less 16 KiB)
1875                 if { [expr abs ($mem1 - $mem2) > 16 + 0.05 * abs ($mem1 + $mem2)] } {
1876                     _log_and_puts log "MEMORY [split $basename /] $casename: [_diff_show_ratio $mem1 $mem2]"
1877                 }
1878             }
1879
1880             # check images
1881             set imglist1 [glob -directory $path1 -types f -tails -nocomplain ${casename}.{png,gif} ${casename}-*.{png,gif} ${casename}_*.{png,gif}]
1882             set imglist2 [glob -directory $path2 -types f -tails -nocomplain ${casename}.{png,gif} ${casename}-*.{png,gif} ${casename}_*.{png,gif}]
1883             _list_diff $imglist1 $imglist2 imgin1 imgin2 imgcommon
1884             if { "$verbose" > 1 } {
1885                 if { [llength $imgin1] > 0 } { _log_and_puts log "Only in $path1: $imgin1" }
1886                 if { [llength $imgin2] > 0 } { _log_and_puts log "Only in $path2: $imgin2" }
1887             }
1888             foreach imgfile $imgcommon {
1889                 # if { $verbose > 1 } { _log_and_puts log "Checking [split basename /] $casename: $imgfile" }
1890                 set diffile [_diff_img_name $dir1 $dir2 $basename $imgfile]
1891                 if { [catch {diffimage [file join $dir1 $basename $imgfile] \
1892                                        [file join $dir2 $basename $imgfile] \
1893                                        0 0 0 $diffile} diff] } {
1894                     _log_and_puts log "IMAGE [split $basename /] $casename: $imgfile cannot be compared"
1895                     file delete -force $diffile ;# clean possible previous result of diffimage
1896                 } elseif { $diff != 0 } {
1897                     _log_and_puts log "IMAGE [split $basename /] $casename: $imgfile differs"
1898                 } else {
1899                     file delete -force $diffile ;# clean useless artifact of diffimage
1900                 }
1901             }
1902         }
1903         
1904         # report CPU and memory difference in group if it is greater than 10%
1905         if { [expr abs ($gcpu1 - $gcpu2) > 0.5 + 0.005 * abs ($gcpu1 + $gcpu2)] } {
1906             _log_and_puts log "CPU [split $basename /]: [_diff_show_ratio $gcpu1 $gcpu2]"
1907         }
1908         if { [expr abs ($gmem1 - $gmem2) > 16 + 0.005 * abs ($gmem1 + $gmem2)] } {
1909             _log_and_puts log "MEMORY [split $basename /]: [_diff_show_ratio $gmem1 $gmem2]"
1910         }
1911     }
1912
1913     if { "$_statvar" == "" } {
1914         _log_and_puts log "Total MEMORY difference: [_diff_show_ratio $stat(mem1) $stat(mem2)]"
1915         _log_and_puts log "Total CPU difference: [_diff_show_ratio $stat(cpu1) $stat(cpu2)]"
1916     }
1917 }
1918
1919 # Auxiliary procedure to save log of results comparison to file
1920 proc _log_html_diff {file log dir1 dir2 highlight_percent} {
1921     # create missing directories as needed
1922     catch {file mkdir [file dirname $file]}
1923
1924     # try to open a file
1925     if [catch {set fd [open $file w]} res] {
1926         error "Error saving log file $file: $res"
1927     }
1928     
1929     # print header
1930     puts $fd "<html><head><title>Diff $dir1 vs. $dir2</title></head><body>"
1931     puts $fd "<h1>Comparison of test results:</h1>"
1932     puts $fd "<h2>Version A - $dir1</h2>"
1933     puts $fd "<h2>Version B - $dir2</h2>"
1934
1935     # print log body, trying to add HTML links to script files on lines like
1936     # "Executing <filename>..."
1937     puts $fd "<pre>"
1938     set logpath [file split [file normalize $file]]
1939     foreach line $log {
1940         # put a line; highlight considerable (> ${highlight_percent}%) deviations of CPU and memory
1941         if { [regexp "\[\\\[](\[0-9.e+-]+)%\[\]]" $line res value] && 
1942              [expr abs($value)] > ${highlight_percent} } {
1943             puts $fd "<table><tr><td bgcolor=\"[expr $value > 0 ? \"red\" : \"lightgreen\"]\">$line</td></tr></table>"
1944         } else {
1945             puts $fd $line
1946         }
1947
1948         # add images
1949         if { [regexp {IMAGE[ \t]+([^:]+):[ \t]+([A-Za-z0-9_.-]+)} $line res case img] } {
1950             if { [catch {eval file join "" [lrange $case 0 end-1]} gridpath] } {
1951                 # note: special handler for the case if test grid directoried are compared directly
1952                 set gridpath ""
1953             }
1954             set img1 "<img src=\"[_make_url $file [file join $dir1 $gridpath $img]]\">"
1955             set img2 "<img src=\"[_make_url $file [file join $dir2 $gridpath $img]]\">"
1956
1957             set difffile [_diff_img_name $dir1 $dir2 $gridpath $img]
1958             if { [file exists $difffile] } {
1959                 set imgd "<img src=\"[_make_url $file $difffile]\">"
1960             } else {
1961                 set imgd "N/A"
1962             }
1963
1964             puts $fd "<table><tr><th><abbr title=\"$dir1\">Version A</abbr></th><th><abbr title=\"$dir2\">Version B</abbr></th><th>Different pixels</th></tr>"
1965             puts $fd "<tr><td>$img1</td><td>$img2</td><td>$imgd</td></tr></table>"
1966         }
1967     }
1968     puts $fd "</pre></body></html>"
1969
1970     close $fd
1971     return
1972 }
1973
1974 # get number of CPUs on the system
1975 proc _get_nb_cpus {} {
1976     global tcl_platform env
1977
1978     if { "$tcl_platform(platform)" == "windows" } {
1979         # on Windows, take the value of the environment variable 
1980         if { [info exists env(NUMBER_OF_PROCESSORS)] &&
1981              ! [catch {expr $env(NUMBER_OF_PROCESSORS) > 0} res] && $res >= 0 } {
1982             return $env(NUMBER_OF_PROCESSORS)
1983         }
1984     } elseif { "$tcl_platform(os)" == "Linux" } {
1985         # on Linux, take number of logical processors listed in /proc/cpuinfo
1986         if { [catch {open "/proc/cpuinfo" r} fd] } { 
1987             return 0 ;# should never happen, but...
1988         }
1989         set nb 0
1990         while { [gets $fd line] >= 0 } {
1991             if { [regexp {^processor[ \t]*:} $line] } {
1992                 incr nb
1993             }
1994         }
1995         close $fd
1996         return $nb
1997     } elseif { "$tcl_platform(os)" == "Darwin" } {
1998         # on MacOS X, call sysctl command
1999         if { ! [catch {exec sysctl hw.ncpu} ret] && 
2000              [regexp {^hw[.]ncpu[ \t]*:[ \t]*([0-9]+)} $ret res nb] } {
2001             return $nb
2002         }
2003     }
2004
2005     # if cannot get good value, return 0 as default
2006     return 0
2007 }
2008
2009 # check two files for difference
2010 proc _diff_files {file1 file2} {
2011     set fd1 [open $file1 "r"]
2012     set fd2 [open $file2 "r"]
2013
2014     set differ f
2015     while {! $differ} {
2016         set nb1 [gets $fd1 line1]
2017         set nb2 [gets $fd2 line2]
2018         if { $nb1 != $nb2 } { set differ t; break }
2019         if { $nb1 < 0 } { break }
2020         if { [string compare $line1 $line2] } {
2021             set differ t
2022         }
2023     }
2024
2025     close $fd1
2026     close $fd2
2027
2028     return $differ
2029 }
2030
2031 # Check if file is in DOS encoding.
2032 # This check is done by presence of \r\n combination at the end of the first 
2033 # line (i.e. prior to any other \n symbol).
2034 # Note that presence of non-ascii symbols typically used for recognition
2035 # of binary files is not suitable since some IGES and STEP files contain
2036 # non-ascii symbols.
2037 # Special check is added for PNG files which contain \r\n in the beginning.
2038 proc _check_dos_encoding {file} {
2039     set fd [open $file rb]
2040     set isdos f
2041     if { [gets $fd line] && [regexp {.*\r$} $line] && 
2042          ! [regexp {^.PNG} $line] } {
2043         set isdos t
2044     }
2045     close $fd
2046     return $isdos
2047 }
2048
2049 # procedure to recognize format of a data file by its first symbols (for OCCT 
2050 # BREP and geometry DRAW formats, IGES, and STEP) and extension (all others)
2051 proc _check_file_format {file} {
2052     set fd [open $file rb]
2053     set line [read $fd 1024]
2054     close $fd
2055
2056     set warn f
2057     set ext [file extension $file]
2058     set format unknown
2059     if { [regexp {^DBRep_DrawableShape} $line] } {
2060         set format BREP
2061         if { "$ext" != ".brep" && "$ext" != ".rle" && 
2062              "$ext" != ".draw" && "$ext" != "" } {
2063             set warn t
2064         }
2065     } elseif { [regexp {^DrawTrSurf_} $line] } {
2066         set format DRAW
2067         if { "$ext" != ".rle" && 
2068              "$ext" != ".draw" && "$ext" != "" } {
2069             set warn t
2070         }
2071     } elseif { [regexp {^[ \t]*ISO-10303-21} $line] } {
2072         set format STEP
2073         if { "$ext" != ".step" && "$ext" != ".stp" } {
2074             set warn t
2075         }
2076     } elseif { [regexp {^.\{72\}S[0 ]\{6\}1} $line] } {
2077         set format IGES
2078         if { "$ext" != ".iges" && "$ext" != ".igs" } {
2079             set warn t
2080         }
2081     } elseif { "$ext" == ".igs" } {
2082         set format IGES
2083     } elseif { "$ext" == ".stp" } {
2084         set format STEP
2085     } else {
2086         set format [string toupper [string range $ext 1 end]]
2087     }
2088     
2089     if { $warn } {
2090         puts "$file: Warning: extension ($ext) does not match format ($format)"
2091     }
2092
2093     return $format
2094 }
2095
2096 # procedure to load file knowing its format
2097 proc load_data_file {file format shape} {
2098     switch $format {
2099         BREP { uplevel restore $file $shape }
2100         DRAW { uplevel restore $file $shape }
2101         IGES { pload XSDRAW; uplevel igesbrep $file $shape * }
2102         STEP { pload XSDRAW; uplevel stepread $file __a *; uplevel renamevar __a_1 $shape }
2103         STL  { pload XSDRAW; uplevel readstl $shape $file }
2104         default { error "Cannot read $format file $file" }
2105     }
2106 }
2107
2108 # procedure to get name of temporary directory,
2109 # ensuring it is existing and writeable 
2110 proc _get_temp_dir {} {
2111     global env tcl_platform
2112
2113     # check typical environment variables 
2114     foreach var {TempDir Temp Tmp} {
2115         # check different case
2116         foreach name [list [string toupper $var] $var [string tolower $var]] {
2117             if { [info exists env($name)] && [file isdirectory $env($name)] &&
2118                  [file writable $env($name)] } {
2119                 return [regsub -all {\\} $env($name) /]
2120             }
2121         }
2122     }
2123
2124     # check platform-specific locations
2125     set fallback tmp
2126     if { "$tcl_platform(platform)" == "windows" } {
2127         set paths "c:/TEMP c:/TMP /TEMP /TMP"
2128         if { [info exists env(HOMEDRIVE)] && [info exists env(HOMEPATH)] } {
2129             set fallback [regsub -all {\\} "$env(HOMEDRIVE)$env(HOMEPATH)/tmp" /]
2130         }
2131     } else {
2132         set paths "/tmp /var/tmp /usr/tmp"
2133         if { [info exists env(HOME)] } {
2134             set fallback "$env(HOME)/tmp"
2135         }
2136     }
2137     foreach dir $paths {
2138         if { [file isdirectory $dir] && [file writable $dir] } {
2139             return $dir
2140         }
2141     }
2142
2143     # fallback case: use subdir /tmp of home or current dir
2144     file mkdir $fallback
2145     return $fallback
2146 }
2147
2148 # extract of code from testgrid command used to process jobs running in 
2149 # parallel until number of jobs in the queue becomes equal or less than 
2150 # specified value
2151 proc _testgrid_process_jobs {worker {nb_ok 0}} {
2152     # bind local vars to variables of the caller procedure
2153     upvar log log
2154     upvar logdir logdir
2155     upvar job_def job_def
2156     upvar nbpooled nbpooled
2157     upvar userbreak userbreak
2158     upvar refresh refresh
2159     upvar refresh_timer refresh_timer
2160
2161     catch {tpool::resume $worker}
2162     while { ! $userbreak && $nbpooled > $nb_ok } {
2163         foreach job [tpool::wait $worker [array names job_def]] {
2164             eval _log_test_case \[tpool::get $worker $job\] $job_def($job) log
2165             unset job_def($job)
2166             incr nbpooled -1
2167         }
2168
2169         # check for user break
2170         if { "[info commands dbreak]" == "dbreak" && [catch dbreak] } {
2171             set userbreak 1
2172         }
2173
2174         # update summary log with requested period
2175         if { $logdir != "" && $refresh > 0 && [clock seconds] > $refresh_timer + $refresh } {
2176             _log_summarize $logdir $log
2177             set refresh_timer [clock seconds]
2178         }
2179     }
2180     catch {tpool::suspend $worker}
2181 }
2182
2183 help checkcolor {
2184   Check pixel color.
2185   Use: checkcolor x y red green blue
2186   x y - pixel coordinates
2187   red green blue - expected pixel color (values from 0 to 1)
2188   Function check color with tolerance (5x5 area)
2189 }
2190 # Procedure to check color using command vreadpixel with tolerance
2191 proc checkcolor { coord_x coord_y rd_get gr_get bl_get } {
2192     puts "Coordinate x = $coord_x"
2193     puts "Coordinate y = $coord_y"
2194     puts "RED color of RGB is $rd_get"
2195     puts "GREEN color of RGB is $gr_get"
2196     puts "BLUE color of RGB is $bl_get"
2197
2198     if { $coord_x <= 1 || $coord_y <= 1 } {
2199         puts "Error : minimal coordinate is x = 2, y = 2. But we have x = $coord_x y = $coord_y"
2200         return -1
2201     }
2202
2203     set color ""
2204     catch { [set color "[vreadpixel ${coord_x} ${coord_y} rgb]"] }
2205     if {"$color" == ""} {
2206         puts "Error : Pixel coordinates (${position_x}; ${position_y}) are out of view"
2207     }
2208     set rd [lindex $color 0]
2209     set gr [lindex $color 1]
2210     set bl [lindex $color 2]
2211     set rd_int [expr int($rd * 1.e+05)]
2212     set gr_int [expr int($gr * 1.e+05)]
2213     set bl_int [expr int($bl * 1.e+05)]
2214     set rd_ch [expr int($rd_get * 1.e+05)]
2215     set gr_ch [expr int($gr_get * 1.e+05)]
2216     set bl_ch [expr int($bl_get * 1.e+05)]
2217
2218     if { $rd_ch != 0 } {
2219         set tol_rd [expr abs($rd_ch - $rd_int)/$rd_ch]
2220     } else {
2221         set tol_rd $rd_int
2222     }
2223     if { $gr_ch != 0 } {
2224         set tol_gr [expr abs($gr_ch - $gr_int)/$gr_ch]
2225     } else {
2226         set tol_gr $gr_int
2227     }
2228     if { $bl_ch != 0 } {
2229         set tol_bl [expr abs($bl_ch - $bl_int)/$bl_ch]
2230     } else {
2231         set tol_bl $bl_int
2232     }
2233
2234     set status 0
2235     if { $tol_rd > 0.2 } {
2236         puts "Warning : RED light of additive color model RGB is invalid"
2237         set status 1
2238     }
2239     if { $tol_gr > 0.2 } {
2240         puts "Warning : GREEN light of additive color model RGB is invalid"
2241         set status 1
2242     }
2243     if { $tol_bl > 0.2 } {
2244         puts "Warning : BLUE light of additive color model RGB is invalid"
2245         set status 1
2246     }
2247
2248     if { $status != 0 } {
2249         puts "Warning : Colors of default coordinate are not equal"
2250     }
2251
2252     global stat
2253     if { $tol_rd > 0.2 || $tol_gr > 0.2 || $tol_bl > 0.2 } {
2254         set info [_checkpoint $coord_x $coord_y $rd_ch $gr_ch $bl_ch]
2255         set stat [lindex $info end]
2256         if { ${stat} != 1 } {
2257             puts "Error : Colors are not equal in default coordinate and in the near coordinates too"
2258             return $stat
2259         } else {
2260             puts "Point with valid color was found"
2261             return $stat
2262         }
2263     } else {
2264         set stat 1
2265     }
2266 }
2267
2268 # Procedure to check color in the point near default coordinate
2269 proc _checkpoint {coord_x coord_y rd_ch gr_ch bl_ch} {
2270     set x_start [expr ${coord_x} - 2]
2271     set y_start [expr ${coord_y} - 2]
2272     set mistake 0
2273     set i 0
2274     while { $mistake != 1 && $i <= 5 } {
2275         set j 0
2276         while { $mistake != 1 && $j <= 5 } {
2277             set position_x [expr ${x_start} + $j]
2278             set position_y [expr ${y_start} + $i]
2279             puts $position_x
2280             puts $position_y
2281
2282             set color ""
2283             catch { [set color "[vreadpixel ${position_x} ${position_y} rgb]"] }
2284             if {"$color" == ""} {
2285                 puts "Warning : Pixel coordinates (${position_x}; ${position_y}) are out of view"
2286                 incr j
2287                 continue
2288             }
2289             set rd [lindex $color 0]
2290             set gr [lindex $color 1]
2291             set bl [lindex $color 2]
2292             set rd_int [expr int($rd * 1.e+05)]
2293             set gr_int [expr int($gr * 1.e+05)]
2294             set bl_int [expr int($bl * 1.e+05)]
2295
2296             if { $rd_ch != 0 } {
2297                 set tol_rd [expr abs($rd_ch - $rd_int)/$rd_ch]
2298             } else {
2299                 set tol_rd $rd_int
2300             }
2301             if { $gr_ch != 0 } {
2302                 set tol_gr [expr abs($gr_ch - $gr_int)/$gr_ch]
2303             } else {
2304                 set tol_gr $gr_int
2305             }
2306             if { $bl_ch != 0 } {
2307                 set tol_bl [expr abs($bl_ch - $bl_int)/$bl_ch]
2308             } else {
2309                 set tol_bl $bl_int
2310             }
2311
2312             if { $tol_rd > 0.2 || $tol_gr > 0.2 || $tol_bl > 0.2 } {
2313                 puts "Warning : Point with true color was not found near default coordinates"
2314                 set mistake 0
2315             } else {
2316                 set mistake 1
2317             }
2318             incr j
2319         }
2320         incr i
2321     }
2322     return $mistake
2323 }