1b00089ec2d599dee8b34e931cc07cff4a85a0d1
[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 }
595 proc testdiff {dir1 dir2 args} {
596     if { "$dir1" == "$dir2" } {
597         error "Input directories are the same"
598     }
599
600     ######################################################
601     # check arguments
602     ######################################################
603
604     # treat options
605     set logfile [file join $dir1 "diff-[file tail $dir2].log"]
606     set basename ""
607     set status "same"
608     set verbose 3
609     for {set narg 0} {$narg < [llength $args]} {incr narg} {
610         set arg [lindex $args $narg]
611
612         # log file name
613         if { $arg == "-save" } {
614             incr narg
615             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
616                 set logfile [lindex $args $narg]
617             } else {
618                 error "Error: Option -save must be followed by log file name"
619             } 
620             continue
621         }
622
623         # status filter
624         if { $arg == "-status" } {
625             incr narg
626             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
627                 set status [lindex $args $narg]
628             } else { set status "" }
629             if { "$status" != "same" && "$status" != "all" && "$status" != "ok" } {
630                 error "Error: Option -status must be followed by one of \"same\", \"all\", or \"ok\""
631             }
632             continue
633         }
634
635         # verbose level
636         if { $arg == "-verbose" } {
637             incr narg
638             if { $narg < [llength $args] && ! [regexp {^-} [lindex $args $narg]] } { 
639                 set verbose [expr [lindex $args $narg]]
640             } else {
641                 error "Error: Option -verbose must be followed by integer verbose level"
642             }
643             continue
644         }
645
646         if { [regexp {^-} $arg] } {
647             error "Error: unsupported option \"$arg\""
648         }
649
650         # non-option arguments form a subdirectory path
651         set basename [file join $basename $arg]
652     }
653
654     # run diff procedure (recursive)
655     _test_diff $dir1 $dir2 $basename $status $verbose log
656
657     # save result to log file
658     if { "$logfile" != "" } {
659         _log_save $logfile [join $log "\n"]
660         _log_html_diff "[file rootname $logfile].html" $log $dir1 $dir2
661         puts "Log is saved to $logfile (and .html)"
662     }
663
664     return
665 }
666
667 # Procedure to check data file before adding it to repository
668 help testfile {
669   Check data file and prepare it for putting to test data files repository.
670   Use: testfile [filelist]
671
672   Will report if:
673   - data file (non-binary) is in DOS encoding (CR/LF)
674   - same data file (with same or another name) already exists in the repository
675   - another file with the same name already exists 
676   Note that names are assumed to be case-insensitive (for Windows).
677
678   Unless the file is already in the repository, tries to load it, reports
679   the recognized file format, file size, number of faces and edges in the 
680   loaded shape (if any), and makes snapshot (in the temporary directory).
681   Finally it advises whether the file should be put to public section of the 
682   repository.
683 }
684 proc testfile {filelist} {
685     global env
686
687     # check that CSF_TestDataPath is defined
688     if { ! [info exists env(CSF_TestDataPath)] } {
689         error "Environment variable CSF_TestDataPath must be defined!"
690     }
691
692     # build registry of existing data files (name -> path) and (size -> path)
693     puts "Checking available test data files..."
694     foreach dir [_split_path $env(CSF_TestDataPath)] {
695         while {[llength $dir] != 0} {
696             set curr [lindex $dir 0]
697             set dir [lrange $dir 1 end]
698             eval lappend dir [glob -nocomplain -directory $curr -type d *]
699             foreach file [glob -nocomplain -directory $curr -type f *] {
700                 set name [file tail $file]
701                 set name_lower [string tolower $name]
702
703                 # check that the file is not in DOS encoding
704                 if { [_check_dos_encoding $file] } {
705                     puts "Warning: file $file is in DOS encoding; was this intended?"
706                 }
707                 _check_file_format $file
708
709                 # check if file with the same name is present twice or more
710                 if { [info exists names($name_lower)] } {
711                     puts "Error: more than one file with name $name is present in the repository:"
712                     if { [_diff_files $file $names($name_lower)] } {
713                         puts "(files are different by content)"
714                     } else {
715                         puts "(files are same by content)"
716                     }
717                     puts "--> $file"
718                     puts "--> $names($name_lower)"
719                     continue
720                 } 
721                 
722                 # check if file with the same content exists
723                 set size [file size $file]
724                 if { [info exists sizes($size)] } {
725                     foreach other $sizes($size) {
726                         if { ! [_diff_files $file $other] } {
727                             puts "Warning: two files with the same content found:"
728                             puts "--> $file"
729                             puts "--> $other"
730                         }
731                     }
732                 }
733
734                 # add the file to the registry
735                 set names($name_lower) $file
736                 lappend sizes($size) $file
737             }
738         }
739     }
740     if { [llength $filelist] <= 0 } { return }
741
742     # check the new files
743     set has_images f
744     puts "Checking new file(s)..."
745     foreach file $filelist {
746         # check for DOS encoding
747         if { [_check_dos_encoding $file] } {
748             puts "$file: Warning: DOS encoding detected"
749         }
750
751         set name [file tail $file]
752         set name_lower [string tolower $name]
753
754         # check for presence of the file with same name
755         if { [info exists names($name_lower)] } {
756             if { [_diff_files $file $names($name_lower)] } {
757                 puts "$file: Error: name is already used by existing file\n--> $names($name_lower)"
758             } else {
759                 puts "$file: OK: already in the repository \n--> $names($name_lower)"
760                 continue
761             }
762         }
763                 
764         # check if file with the same content exists
765         set size [file size $file]
766         if { [info exists sizes($size)] } {
767             set found f
768             foreach other $sizes($size) {
769                 if { ! [_diff_files $file $other] } {
770                      puts "$file: OK: the same file is already present under name [file tail $other]\n--> $other"
771                      set found t
772                      break
773                 }
774             }
775             if { $found } { continue }
776         }
777
778         # try to read the file
779         set format [_check_file_format $file]
780         if { [catch {uplevel load_data_file $file $format a}] } {
781             puts "$file: Error: Cannot read as $format file"
782             continue
783         }
784
785         # get number of faces and edges
786         set edges 0
787         set faces 0
788         set nbs [uplevel nbshapes a]
789         regexp {EDGE[ \t:]*([0-9]+)} $nbs res edges
790         regexp {FACE[ \t:]*([0-9]+)} $nbs res faces
791
792         # classify; first check file size and number of faces and edges
793         if { $size < 95000 && $faces < 20 && $edges < 100 } {
794             set dir public
795         } else {
796             set dir private
797             # check if one of names of that file corresponds to typical name for 
798             # MDTV bugs or has extension .rle, this should be old model
799             if { [regexp -nocase {.*(cts|ats|pro|buc|ger|fra|usa|uki)[0-9]+.*} $name] ||
800                  [regexp -nocase {[.]rle\y} $name] } {
801                 set dir old
802             }
803         }
804
805         # add stats
806         puts "$file: $format size=[expr $size / 1024] KiB, nbfaces=$faces, nbedges=$edges -> $dir"
807
808         set tmpdir [_get_temp_dir]
809         file mkdir $tmpdir/$dir
810
811         # make snapshot
812         pload AISV
813         uplevel vdisplay a
814         uplevel vfit
815         uplevel vzfit
816         uplevel vdump $tmpdir/$dir/[file rootname [file tail $file]].png
817         set has_images t
818     }
819     if { $has_images } {
820         puts "Snapshots are saved in subdirectory [_get_temp_dir]"
821     }
822 }
823
824 # Procedure to locate data file for test given its name.
825 # The search is performed assuming that the function is called
826 # from the test case script; the search order is:
827 # - subdirectory "data" of the test script (grid) folder
828 # - subdirectories in environment variable CSF_TestDataPath
829 # - subdirectory set by datadir command
830 # If file is not found, raises Tcl error.
831 proc locate_data_file {filename} {
832     global env groupname gridname casename
833
834     # check if the file is located in the subdirectory data of the script dir
835     set scriptfile [info script]
836     if { $scriptfile != "" } {
837         set path [file join [file dirname $scriptfile] data $filename]
838         if { [file exists $path] } {
839             return [file normalize $path]
840         }
841     }
842
843     # check sub-directories in paths indicated by CSF_TestDataPath
844     if { [info exists env(CSF_TestDataPath)] } {
845         foreach dir [_split_path $env(CSF_TestDataPath)] {
846             while {[llength $dir] != 0} { 
847                 set name [lindex $dir 0]
848                 set dir [lrange $dir 1 end]
849                 # skip directories starting with dot
850                 if { [regexp {^[.]} $name] } { continue }
851                 if { [file exists $name/$filename] } {
852                     return [file normalize $name/$filename]
853                 }
854                 eval lappend dir [glob -nocomplain -directory $name -type d *]
855             }
856         }
857     }
858
859     # check current datadir
860     if { [file exists [uplevel datadir]/$filename] } {
861         return [file normalize [uplevel datadir]/$filename]
862     }
863
864     # raise error
865     error [join [list "File $filename could not be found" \
866                       "(should be in paths indicated by CSF_TestDataPath environment variable, " \
867                       "or in subfolder data in the script directory)"] "\n"]
868 }
869
870 # Internal procedure to find test case indicated by group, grid, and test case names;
871 # returns:
872 # - dir: path to the base directory of the tests group
873 # - gridname: actual name of the grid
874 # - casefile: path to the test case script 
875 # if no such test is found, raises error with appropriate message
876 proc _get_test {group grid casename _dir _gridname _casefile} {
877     upvar $_dir dir
878     upvar $_gridname gridname
879     upvar $_casefile casefile
880
881     global env
882  
883     # check that environment variable defining paths to test scripts is defined
884     if { ! [info exists env(CSF_TestScriptsPath)] || 
885          [llength $env(CSF_TestScriptsPath)] <= 0 } {
886         error "Error: Environment variable CSF_TestScriptsPath is not defined"
887     }
888
889     # iterate by all script paths
890     foreach dir [_split_path $env(CSF_TestScriptsPath)] {
891         # protection against empty paths
892         set dir [string trim $dir]
893         if { $dir == "" } { continue }
894
895         # check that directory exists
896         if { ! [file isdirectory $dir] } {
897             puts "Warning: directory $dir listed in CSF_TestScriptsPath does not exist, skipped"
898             continue
899         }
900
901         # check if test group with given name exists in this dir
902         # if not, continue to the next test dir
903         if { ! [file isdirectory $dir/$group] } { continue }
904
905         # check that grid with given name (possibly alias) exists; stop otherwise
906         set gridname $grid
907         if { ! [file isdirectory $dir/$group/$gridname] } {
908             # check if grid is named by alias rather than by actual name
909             if { [file exists $dir/$group/grids.list] } {
910                 set fd [open $dir/$group/grids.list]
911                 while { [gets $fd line] >= 0 } {
912                     if { [regexp "\[ \t\]*\#.*" $line] } { continue }
913                     if { [regexp "^$grid\[ \t\]*\(\[A-Za-z0-9_.-\]+\)\$" $line res gridname] } {
914                         break
915                     }
916                 }
917                 close $fd
918             }
919         }
920         if { ! [file isdirectory $dir/$group/$gridname] } { continue }
921
922         # get actual file name of the script; stop if it cannot be found
923         set casefile $dir/$group/$gridname/$casename
924         if { ! [file exists $casefile] } {
925             # check if this grid is aliased to another one
926             if { [file exists $dir/$group/$gridname/cases.list] } {
927                 set fd [open $dir/$group/$gridname/cases.list]
928                 if { [gets $fd line] >= 0 } {
929                     set casefile [file normalize $dir/$group/$gridname/[string trim $line]/$casename]
930                 }
931                 close $fd
932             }
933         }
934         if { [file exists $casefile] } { 
935             # normal return
936             return 
937         }
938     }
939
940     # coming here means specified test is not found; report error
941     error [join [list "Error: test case $group / $grid / $casename is not found in paths listed in variable" \
942                      "CSF_TestScriptsPath (current value is \"$env(CSF_TestScriptsPath)\")"] "\n"]
943 }
944
945 # Internal procedure to run test case indicated by base directory, 
946 # grid and grid names, and test case file path.
947 # The log can be obtained by command "dlog get".
948 proc _run_test {scriptsdir group gridname casefile echo} {
949     global env
950
951     # start timer
952     uplevel dchrono _timer reset
953     uplevel dchrono _timer start
954     catch {uplevel meminfo h} membase
955
956     # enable commands logging; switch to old-style mode if dlog command is not present
957     set dlog_exists 1
958     if { [catch {dlog reset}] } {
959         set dlog_exists 0
960     } elseif { $echo } {
961         decho on
962     } else {
963         dlog reset
964         dlog on
965         rename puts puts-saved
966         proc puts args { 
967             global _tests_verbose
968
969             # log only output to stdout and stderr, not to file!
970             if {[llength $args] > 1} {
971                 set optarg [lindex $args end-1]
972                 if { $optarg == "stdout" || $optarg == "stderr" || $optarg == "-newline" } {
973                     dlog add [lindex $args end]
974                 } else {
975                     eval puts-saved $args
976                 }
977             } else {
978                 dlog add [lindex $args end]
979             }
980         }
981     }
982
983     # evaluate test case 
984     set tmp_imagedir 0
985     if [catch {
986         # set variables identifying test case
987         uplevel set casename [file tail $casefile]
988         uplevel set groupname $group
989         uplevel set gridname $gridname
990         uplevel set dirname  $scriptsdir
991
992         # set path for saving of log and images (if not yet set) to temp dir
993         if { ! [uplevel info exists imagedir] } {
994             uplevel set test_image \$casename
995
996             # create subdirectory in temp named after group and grid with timestamp
997             set rootlogdir [_get_temp_dir]
998         
999             set imagedir "${group}-${gridname}-${::casename}-[clock format [clock seconds] -format {%Y-%m-%dT%Hh%Mm%Ss}]"
1000             set imagedir [file normalize ${rootlogdir}/$imagedir]
1001
1002             if { [catch {file mkdir $imagedir}] || ! [file writable $imagedir] ||
1003                  ! [catch {glob -directory $imagedir *}] } {
1004 #                puts "Warning: Cannot create directory \"$imagedir\", or it is not empty; \"${rootlogdir}\" is used"
1005                 set imagedir $rootlogdir
1006             }
1007
1008             uplevel set imagedir \"$imagedir\"
1009             set tmp_imagedir 1
1010         }
1011
1012         # execute test scripts 
1013         if { [file exists $scriptsdir/$group/begin] } {
1014             puts "Executing $scriptsdir/$group/begin..."; flush stdout
1015             uplevel source $scriptsdir/$group/begin
1016         }
1017         if { [file exists $scriptsdir/$group/$gridname/begin] } {
1018             puts "Executing $scriptsdir/$group/$gridname/begin..."; flush stdout
1019             uplevel source $scriptsdir/$group/$gridname/begin
1020         }
1021         
1022         puts "Executing $casefile..."; flush stdout
1023         uplevel source $casefile
1024         
1025         if { [file exists $scriptsdir/$group/$gridname/end] } {
1026             puts "Executing $scriptsdir/$group/$gridname/end..."; flush stdout
1027             uplevel source $scriptsdir/$group/$gridname/end
1028         }
1029         if { [file exists $scriptsdir/$group/end] } {
1030             puts "Executing $scriptsdir/$group/end..."; flush stdout
1031             uplevel source $scriptsdir/$group/end
1032         }
1033     } res] {
1034         puts "Tcl Exception: $res"
1035     }
1036
1037     # stop logging
1038     if { $dlog_exists } {
1039         if { $echo } {
1040             decho off
1041         } else {
1042             rename puts {}
1043             rename puts-saved puts
1044             dlog off
1045         }
1046     }
1047
1048     # stop cpulimit killer if armed by the test
1049     cpulimit
1050
1051     # add memory and timing info
1052     set stats ""
1053     if { ! [catch {uplevel meminfo h} memuse] } {
1054         append stats "MEMORY DELTA: [expr ($memuse - $membase) / 1024] KiB\n"
1055     }
1056     uplevel dchrono _timer stop
1057     set time [uplevel dchrono _timer show]
1058     if { [regexp -nocase {CPU user time:[ \t]*([0-9.e-]+)} $time res cpu_usr] } {
1059         append stats "TOTAL CPU TIME: $cpu_usr sec\n"
1060     }
1061     if { $dlog_exists && ! $echo } {
1062         dlog add $stats
1063     } else {
1064         puts $stats
1065     }
1066
1067     # unset global vars
1068     uplevel unset casename groupname gridname dirname
1069     if { $tmp_imagedir } { uplevel unset imagedir test_image }
1070 }
1071
1072 # Internal procedure to check log of test execution and decide if it passed or failed
1073 proc _check_log {dir group gridname casename errors log {_summary {}} {_html_log {}}} {
1074     global env
1075     if { $_summary != "" } { upvar $_summary summary }
1076     if { $_html_log != "" } { upvar $_html_log html_log }
1077     set summary {}
1078     set html_log {}
1079     set errors_log {}
1080
1081 if [catch {
1082
1083     # load definition of 'bad words' indicating test failure
1084     # note that rules are loaded in the order of decreasing priority (grid - group - common),
1085     # thus grid rules will override group ones
1086     set badwords {}
1087     foreach rulesfile [list $dir/$group/$gridname/parse.rules $dir/$group/parse.rules $dir/parse.rules] {
1088         if [catch {set fd [open $rulesfile r]}] { continue }
1089         while { [gets $fd line] >= 0 } {
1090             # skip comments and empty lines
1091             if { [regexp "\[ \t\]*\#.*" $line] } { continue }
1092             if { [string trim $line] == "" } { continue }
1093             # extract regexp
1094             if { ! [regexp {^([^/]*)/([^/]*)/(.*)$} $line res status rexp comment] } { 
1095                 puts "Warning: cannot recognize parsing rule \"$line\" in file $rulesfile"
1096                 continue 
1097             }
1098             set status [string trim $status]
1099             if { $comment != "" } { append status " ([string trim $comment])" }
1100             set rexp [regsub -all {\\b} $rexp {\\y}] ;# convert regexp from Perl to Tcl style
1101             lappend badwords [list $status $rexp]
1102         }
1103         close $fd
1104     }
1105     if { [llength $badwords] <= 0 } { 
1106         puts "Warning: no definition of error indicators found (check files parse.rules)" 
1107     }
1108
1109     # analyse log line-by-line
1110     set todos {}
1111     set status ""
1112     foreach line [split $log "\n"] {
1113         # check if line defines specific treatment of some messages
1114         set deb_info [dversion]
1115         if [regexp -nocase {^[ \s]*TODO ([^:]*):(.*)$} $line res platforms pattern] {
1116             if { [regexp {DEBUG_} $platforms] != 1 } {
1117                 if { ! [regexp -nocase {\mAll\M} $platforms] && 
1118                     ! [regexp -nocase "\\m$env(os_type)\\M" $platforms] } {
1119                     lappend html_log $line
1120                     continue ;# TODO statement is for another platform
1121                 }
1122
1123                 # record TODOs that mark unstable cases
1124                 if { [regexp {[\?]} $platforms] } {
1125                     set todos_unstable([llength $todos]) 1
1126                 }
1127
1128                 lappend todos [regsub -all {\\b} [string trim $pattern] {\\y}] ;# convert regexp from Perl to Tcl style
1129                 lappend html_log [_html_highlight BAD $line]
1130                 continue
1131             }
1132             
1133             if { [regexp "Debug mode" $deb_info] != 1 && [regexp {DEBUG_} $platforms] == 1 } {
1134                 continue
1135             }
1136
1137             if { [regexp "Debug mode" $deb_info] == 1 && [regexp {DEBUG_} $platforms] == 1 } {
1138                 if { ! [regexp -nocase {\mAll\M} $platforms] && 
1139                     ! [regexp -nocase "\\m$env(os_type)\\M" $platforms] } {
1140                     lappend html_log $line
1141                     continue ;# TODO statement is for another platform
1142                 }
1143
1144                 # record TODOs that mark unstable cases
1145                 if { [regexp {[\?]} $platforms] } {
1146                     set todos_unstable([llength $todos]) 1
1147                 }
1148             
1149                 lappend todos [regsub -all {\\b} [string trim $pattern] {\\y}] ;# convert regexp from Perl to Tcl style
1150                 lappend html_log [_html_highlight BAD $line]
1151                 continue
1152             }
1153         }
1154                 
1155         # check for presence of messages indicating test result
1156         set ismarked 0
1157         foreach bw $badwords {
1158             if { [regexp [lindex $bw 1] $line] } { 
1159                 # check if this is known bad case
1160                 set is_known 0
1161                 for {set i 0} {$i < [llength $todos]} {incr i} {
1162                     if { [regexp [lindex $todos $i] $line] } {
1163                         set is_known 1
1164                         incr todo_count($i)
1165                         lappend html_log [_html_highlight BAD $line]
1166                         break
1167                     }
1168                 }
1169
1170                 # if it is not in todo, define status
1171                 if { ! $is_known } {
1172                     set stat [lindex $bw 0 0]
1173                     if {$errors} {
1174                       lappend errors_log $line
1175                     }
1176                     lappend html_log [_html_highlight $stat $line]
1177                     if { $status == "" && $stat != "OK" && ! [regexp -nocase {^IGNOR} $stat] } {
1178                         set status [lindex $bw 0]
1179                     }
1180                 }
1181                 set ismarked 1
1182                 break
1183             }
1184         }
1185         if { ! $ismarked } { 
1186             lappend html_log $line
1187         }
1188     }
1189
1190     # check for presence of TEST COMPLETED statement
1191     if { $status == "" && ! [regexp {TEST COMPLETED} $log] } {
1192         # check whether absence of TEST COMPLETED is known problem
1193         set i [lsearch $todos "TEST INCOMPLETE"]
1194         if { $i >= 0 } {
1195             incr todo_count($i)
1196         } else {
1197             set status "FAILED (no final message is found)"
1198         }
1199     }
1200
1201     # check declared bad cases and diagnose possible improvement 
1202     # (bad case declared but not detected).
1203     # Note that absence of the problem marked by TODO with question mark
1204     # (unstable) is not reported as improvement.
1205     if { $status == "" } {
1206         for {set i 0} {$i < [llength $todos]} {incr i} {
1207             if { ! [info exists todos_unstable($i)] &&
1208                  (! [info exists todo_count($i)] || $todo_count($i) <= 0) } {
1209                 set status "IMPROVEMENT (expected problem TODO no. [expr $i + 1] is not detected)"
1210                 break;
1211             }
1212         }
1213     }
1214
1215     # report test as known bad if at least one of expected problems is found
1216     if { $status == "" && [llength [array names todo_count]] > 0 } {
1217         set status "BAD (known problem)"
1218     }
1219
1220     # report normal OK
1221     if { $status == "" } {set status "OK" }
1222
1223 } res] {
1224     set status "FAILED ($res)"
1225 }
1226
1227     # put final message
1228     _log_and_puts summary "CASE $group $gridname $casename: $status"
1229     set summary [join $summary "\n"]
1230     if {$errors} {
1231       foreach error $errors_log {
1232         _log_and_puts summary "  $error"
1233       }
1234     }
1235     set html_log "[_html_highlight [lindex $status 0] $summary]\n[join $html_log \n]"
1236 }
1237
1238 # Auxiliary procedure putting message to both cout and log variable (list)
1239 proc _log_and_puts {logvar message} {
1240     if { $logvar != "" } { 
1241         upvar $logvar log
1242         lappend log $message
1243     }
1244     puts $message
1245 }
1246
1247 # Auxiliary procedure to log result on single test case
1248 proc _log_test_case {output logdir dir group grid casename logvar} {
1249     upvar $logvar log
1250     set show_errors 0
1251     # check result and make HTML log
1252     _check_log $dir $group $grid $casename $show_errors $output summary html_log
1253     lappend log $summary
1254
1255     # save log to file
1256     if { $logdir != "" } {
1257         _log_html $logdir/$group/$grid/$casename.html $html_log "Test $group $grid $casename"
1258         _log_save $logdir/$group/$grid/$casename.log "$output\n$summary" "Test $group $grid $casename"
1259     }
1260 }
1261
1262 # Auxiliary procedure to save log to file
1263 proc _log_save {file log {title {}}} {
1264     # create missing directories as needed
1265     catch {file mkdir [file dirname $file]}
1266
1267     # try to open a file
1268     if [catch {set fd [open $file w]} res] {
1269         error "Error saving log file $file: $res"
1270     }
1271     
1272     # dump log and close
1273     puts $fd "$title\n"
1274     puts $fd $log
1275     close $fd
1276     return
1277 }
1278
1279 # Auxiliary procedure to make a (relative if possible) URL to a file for 
1280 # inclusion a reference in HTML log
1281 proc _make_url {htmldir file} {
1282     set htmlpath [file split [file normalize $htmldir]]
1283     set filepath [file split [file normalize $file]]
1284     for {set i 0} {$i < [llength $htmlpath]} {incr i} {
1285         if { "[lindex $htmlpath $i]" != "[lindex $filepath $i]" } {
1286             if { $i == 0 } { break }
1287             return "[string repeat "../" [expr [llength $htmlpath] - $i - 1]][eval file join [lrange $filepath $i end]]"
1288         }
1289     }
1290
1291     # if relative path could not be made, return full file URL
1292     return "file://[file normalize $file]"
1293 }
1294
1295 # Auxiliary procedure to save log to file
1296 proc _log_html {file log {title {}}} {
1297     # create missing directories as needed
1298     catch {file mkdir [file dirname $file]}
1299
1300     # try to open a file
1301     if [catch {set fd [open $file w]} res] {
1302         error "Error saving log file $file: $res"
1303     }
1304     
1305     # print header
1306     puts $fd "<html><head><title>$title</title></head><body><h1>$title</h1>"
1307
1308     # add images if present; these should have either PNG, GIF, or JPG extension,
1309     # and start with name of the test script, with optional suffix separated
1310     # by underscore or dash
1311     set imgbasename [file rootname [file tail $file]]
1312     foreach img [lsort [glob -nocomplain -directory [file dirname $file] -tails \
1313                              ${imgbasename}.gif   ${imgbasename}.png   ${imgbasename}.jpg \
1314                              ${imgbasename}_*.gif ${imgbasename}_*.png ${imgbasename}_*.jpg \
1315                              ${imgbasename}-*.gif ${imgbasename}-*.png ${imgbasename}-*.jpg]] {
1316         puts $fd "<p>[file tail $img]<br><img src=\"$img\"/><p>"
1317     }
1318
1319     # print log body, trying to add HTML links to script files on lines like
1320     # "Executing <filename>..."
1321     puts $fd "<pre>"
1322     foreach line [split $log "\n"] {
1323         if { [regexp {Executing[ \t]+([a-zA-Z0-9._/:-]+[^.])} $line res script] &&
1324              [file exists $script] } {
1325             set line [regsub $script $line "<a href=\"[_make_url $file $script]\">$script</a>"]
1326         }
1327         puts $fd $line
1328     }
1329     puts $fd "</pre></body></html>"
1330
1331     close $fd
1332     return
1333 }
1334
1335 # Auxiliary method to make text with HTML highlighting according to status
1336 proc _html_color {status} {
1337     # choose a color for the cell according to result
1338     if { $status == "OK" } { 
1339         return lightgreen
1340     } elseif { [regexp -nocase {^FAIL} $status] } { 
1341         return red
1342     } elseif { [regexp -nocase {^BAD} $status] } { 
1343         return yellow
1344     } elseif { [regexp -nocase {^IMP} $status] } { 
1345         return orange
1346     } elseif { [regexp -nocase {^SKIP} $status] } { 
1347         return gray
1348     } elseif { [regexp -nocase {^IGNOR} $status] } { 
1349         return gray
1350     } else {
1351         puts "Warning: no color defined for status $status, using red as if FAILED"
1352         return red
1353     }
1354 }
1355
1356 # Format text line in HTML to be colored according to the status
1357 proc _html_highlight {status line} {
1358     return "<table><tr><td bgcolor=\"[_html_color $status]\">$line</td></tr></table>"
1359 }
1360
1361 # Internal procedure to generate HTML page presenting log of the tests
1362 # execution in tabular form, with links to reports on individual cases
1363 proc _log_html_summary {logdir log totals regressions improvements total_time} {
1364     global _test_case_regexp
1365
1366     # create missing directories as needed
1367     file mkdir $logdir
1368
1369     # try to open a file and start HTML
1370     if [catch {set fd [open $logdir/summary.html w]} res] {
1371         error "Error creating log file: $res"
1372     }
1373
1374     # write HRML header, including command to refresh log if still in progress
1375     puts $fd "<html><head>"
1376     puts $fd "<title>Tests summary</title>"
1377     if { $total_time == "" } {
1378         puts $fd "<meta http-equiv=\"refresh\" content=\"10\">"
1379     }
1380     puts $fd "<meta http-equiv=\"pragma\" content=\"NO-CACHE\">"
1381     puts $fd "</head><body>"
1382
1383     # put summary
1384     set legend(OK)          "Test passed OK"
1385     set legend(FAILED)      "Test failed (regression)"
1386     set legend(BAD)         "Known problem"
1387     set legend(IMPROVEMENT) "Possible improvement (expected problem not detected)"
1388     set legend(SKIPPED)     "Test skipped due to lack of data file"
1389     puts $fd "<h1>Summary</h1><table>"
1390     foreach nbstat $totals {
1391         set status [lindex $nbstat 1]
1392         if { [info exists legend($status)] } { 
1393             set comment $legend($status) 
1394         } else {
1395             set comment "User-defined status"
1396         }
1397         puts $fd "<tr><td align=\"right\">[lindex $nbstat 0]</td><td bgcolor=\"[_html_color $status]\">$status</td><td>$comment</td></tr>"
1398     }
1399     puts $fd "</table>"
1400
1401     # time stamp and elapsed time info
1402     if { $total_time != "" } { 
1403         puts $fd "<p>Generated on [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S}] on [info hostname]\n<p>"
1404         puts $fd [join [split $total_time "\n"] "<p>"]
1405     } else {
1406         puts $fd "<p>NOTE: This is intermediate summary; the tests are still running! This page will refresh automatically until tests are finished."
1407     }
1408    
1409     # print regressions and improvements
1410     foreach featured [list $regressions $improvements] {
1411         if { [llength $featured] <= 1 } { continue }
1412         set status [string trim [lindex $featured 0] { :}]
1413         puts $fd "<h2>$status</h2>"
1414         puts $fd "<table>"
1415         set groupgrid ""
1416         foreach test [lrange $featured 1 end] {
1417             if { ! [regexp {^(.*)\s+([\w.]+)$} $test res gg name] } {
1418                 set gg UNKNOWN
1419                 set name "Error building short list; check details"
1420             }
1421             if { $gg != $groupgrid } {
1422                 if { $groupgrid != "" } { puts $fd "</tr>" }
1423                 set groupgrid $gg
1424                 puts $fd "<tr><td>$gg</td>"
1425             }
1426             puts $fd "<td bgcolor=\"[_html_color $status]\"><a href=\"[regsub -all { } $gg /]/${name}.html\">$name</a></td>"
1427         }
1428         if { $groupgrid != "" } { puts $fd "</tr>" }
1429         puts $fd "</table>"
1430     }
1431
1432     # put detailed log with TOC
1433     puts $fd "<hr><h1>Details</h1>"
1434     puts $fd "<div style=\"float:right; padding: 10px; border-style: solid; border-color: blue; border-width: 2px;\">"
1435
1436     # process log line-by-line
1437     set group {}
1438     set letter {}
1439     set body {}
1440     foreach line [lsort -dictionary $log] {
1441         # check that the line is case report in the form "CASE group grid name: result (explanation)"
1442         if { ! [regexp $_test_case_regexp $line res grp grd casename result message] } {
1443             continue
1444         }
1445
1446         # start new group
1447         if { $grp != $group } {
1448             if { $letter != "" } { lappend body "</tr></table>" }
1449             set letter {}
1450             set group $grp
1451             set grid {}
1452             puts $fd "<a href=\"#$group\">$group</a><br>"
1453             lappend body "<h2><a name=\"$group\">Group $group</a></h2>"
1454         }
1455
1456         # start new grid
1457         if { $grd != $grid } {
1458             if { $letter != "" } { lappend body "</tr></table>" }
1459             set letter {}
1460             set grid $grd
1461             puts $fd "&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"#$group-$grid\">$grid</a><br>"
1462             lappend body "<h2><a name=\"$group-$grid\">Grid $group $grid</a></h2>"
1463         }
1464
1465         # check if test case name is <letter><digit>; 
1466         # if not, set alnum to period "." to recognize non-standard test name
1467         if { ! [regexp {\A([A-Za-z]{1,2})([0-9]{1,2})\Z} $casename res alnum number] &&
1468              ! [regexp {\A([A-Za-z0-9]+)_([0-9]+)\Z} $casename res alnum number] } {
1469             set alnum $casename
1470         }
1471
1472         # start new row when letter changes or for non-standard names
1473         if { $alnum != $letter || $alnum == "." } {
1474             if { $letter != "" } { 
1475                 lappend body "</tr><tr>" 
1476             } else {
1477                 lappend body "<table><tr>"
1478             }
1479             set letter $alnum
1480         }           
1481
1482         lappend body "<td bgcolor=\"[_html_color $result]\"><a href=\"$group/$grid/${casename}.html\">$casename</a></td>"
1483     }
1484     puts $fd "</div>\n[join $body "\n"]</tr></table>"
1485
1486     # add remaining lines of log as plain text
1487     puts $fd "<h2>Plain text messages</h2>\n<pre>"
1488     foreach line $log {
1489         if { ! [regexp $_test_case_regexp $line] } {
1490             puts $fd "$line"
1491         }
1492     }
1493     puts $fd "</pre>"
1494
1495     # close file and exit
1496     puts $fd "</body>"
1497     close $fd
1498     return
1499 }
1500
1501 # Procedure to dump summary logs of tests
1502 proc _log_summarize {logdir log {total_time {}}} {
1503
1504     # sort log records alphabetically to have the same behavior on Linux and Windows 
1505     # (also needed if tests are run in parallel)
1506     set loglist [lsort -dictionary $log]
1507
1508     # classify test cases by status
1509     foreach line $loglist {
1510         if { [regexp {^CASE ([^:]*): ([[:alnum:]]+).*$} $line res caseid status] } {
1511             lappend stat($status) $caseid
1512         }
1513     }
1514     set totals {}
1515     set improvements {Improvements:}
1516     set regressions {Failed:}
1517     if { [info exists stat] } {
1518         foreach status [lsort [array names stat]] {
1519             lappend totals [list [llength $stat($status)] $status]
1520
1521             # separately count improvements (status starting with IMP) and regressions (all except IMP, OK, BAD, and SKIP)
1522             if { [regexp -nocase {^IMP} $status] } {
1523                 eval lappend improvements $stat($status)
1524             } elseif { $status != "OK" && ! [regexp -nocase {^BAD} $status] && ! [regexp -nocase {^SKIP} $status] } {
1525                 eval lappend regressions $stat($status)
1526             }
1527         }
1528     }
1529
1530     # if time is specified, add totals
1531     if { $total_time != "" } {
1532         if { [llength $improvements] > 1 } {
1533             _log_and_puts log [join $improvements "\n  "]
1534         }
1535         if { [llength $regressions] > 1 } {
1536             _log_and_puts log [join $regressions "\n  "]
1537         }
1538         if { [llength $improvements] == 1 && [llength $regressions] == 1 } {
1539             _log_and_puts log "No regressions"
1540         }
1541         _log_and_puts log "Total cases: [join $totals {, }]"
1542         _log_and_puts log $total_time
1543     }
1544
1545     # save log to files
1546     if { $logdir != "" } {
1547         _log_html_summary $logdir $log $totals $regressions $improvements $total_time
1548         _log_save $logdir/tests.log [join $log "\n"] "Tests summary"
1549     }
1550
1551     return
1552 }
1553
1554 # Internal procedure to generate XML log in JUnit style, for further
1555 # consumption by Jenkins or similar systems.
1556 #
1557 # The output is intended to conform to XML schema supported by Jenkins found at
1558 # 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
1559 #
1560 # The mapping of the fields is inspired by annotated schema of Apache Ant JUnit XML format found at
1561 # http://windyroad.org/dl/Open%20Source/JUnit.xsd
1562 proc _log_xml_summary {logdir filename log include_cout} {
1563     global _test_case_regexp
1564
1565     catch {file mkdir [file dirname $filename]}
1566
1567     # try to open a file and start XML
1568     if [catch {set fd [open $filename w]} res] {
1569         error "Error creating XML summary file $filename: $res"
1570     }
1571     puts $fd "<?xml version='1.0' encoding='utf-8'?>"
1572     puts $fd "<testsuites>"
1573
1574     # prototype for command to generate test suite tag
1575     set time_and_host "timestamp=\"[clock format [clock seconds] -format {%Y-%m-%dT%H:%M:%S}]\" hostname=\"[info hostname]\""
1576     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"}
1577
1578     # sort log and process it line-by-line
1579     set group {}
1580     foreach line [lsort -dictionary $log] {
1581         # check that the line is case report in the form "CASE group grid name: result (explanation)"
1582         if { ! [regexp $_test_case_regexp $line res grp grd casename result message] } {
1583             continue
1584         }
1585         set message [string trim $message " \t\r\n()"]
1586
1587         # start new testsuite for each grid
1588         if { $grp != $group || $grd != $grid } {
1589
1590             # write previous test suite
1591             if [info exists testcases] { eval $cmd_testsuite }
1592
1593             set testcases {}
1594             set nbtests 0
1595             set nberr 0
1596             set nbfail 0
1597             set nbskip 0
1598             set time 0.
1599
1600             set group $grp
1601             set grid $grd
1602         }
1603
1604         incr nbtests
1605          
1606         # parse test log and get its CPU time
1607         set testout {}
1608         set add_cpu {}
1609         if { [catch {set fdlog [open $logdir/$group/$grid/${casename}.log r]} ret] } { 
1610             puts "Error: cannot open $logdir/$group/$grid/${casename}.log: $ret"
1611         } else {
1612             while { [gets $fdlog logline] >= 0 } {
1613                 if { $include_cout } {
1614                     append testout "$logline\n"
1615                 }
1616                 if [regexp -nocase {TOTAL CPU TIME:\s*([\d.]+)\s*sec} $logline res cpu] {
1617                     set add_cpu " time=\"$cpu\""
1618                     set time [expr $time + $cpu]
1619                 }
1620             }
1621             close $fdlog
1622         }
1623         if { ! $include_cout } {
1624             set testout "$line\n"
1625         }
1626
1627         # record test case with its output and status
1628         # Mapping is: SKIPPED, BAD, and OK to OK, all other to failure
1629         append testcases "\n  <testcase name=\"$casename\"$add_cpu status=\"$result\">\n"
1630         append testcases "\n    <system-out>\n$testout    </system-out>"
1631         if { $result != "OK" } {
1632             if { [regexp -nocase {^SKIP} $result] } {
1633                 incr nberr
1634                 append testcases "\n    <error name=\"$result\" message=\"$message\"/>"
1635             } elseif { [regexp -nocase {^BAD} $result] } {
1636                 incr nbskip
1637                 append testcases "\n    <skipped>$message</skipped>"
1638             } else {
1639                 incr nbfail
1640                 append testcases "\n    <failure name=\"$result\" message=\"$message\"/>"
1641             }
1642         }
1643         append testcases "\n  </testcase>"
1644     }
1645
1646     # write last test suite
1647     if [info exists testcases] { eval $cmd_testsuite }
1648
1649     # the end
1650     puts $fd "</testsuites>"
1651     close $fd
1652     return
1653 }
1654
1655 # define custom platform name 
1656 proc _tests_platform_def {} {
1657     global env tcl_platform
1658
1659     if [info exists env(os_type)] { return }
1660     set env(os_type) $tcl_platform(platform)
1661         if { $tcl_platform(os) == "Linux" } {
1662         set env(os_type) Linux
1663     }
1664         if { $tcl_platform(os) == "Darwin" } {
1665         set env(os_type) MacOS
1666     } 
1667 }
1668 _tests_platform_def
1669
1670 # Auxiliary procedure to split path specification (usually defined by
1671 # environment variable) into list of directories or files
1672 proc _split_path {pathspec} {
1673     global tcl_platform
1674
1675     # first replace all \ (which might occur on Windows) by /  
1676     regsub -all "\\\\" $pathspec "/" pathspec
1677
1678     # split path by platform-specific separator
1679     return [split $pathspec [_path_separator]]
1680 }
1681
1682 # Auxiliary procedure to define platform-specific separator for directories in
1683 # path specification
1684 proc _path_separator {} {
1685     global tcl_platform
1686
1687     # split path by platform-specific separator
1688     if { $tcl_platform(platform) == "windows" } {
1689         return ";"
1690     } else {
1691         return ":"
1692     }
1693 }
1694
1695 # Procedure to make a diff and common of two lists
1696 proc _list_diff {list1 list2 _in1 _in2 _common} {
1697     upvar $_in1 in1
1698     upvar $_in2 in2
1699     upvar $_common common
1700
1701     set in1 {}
1702     set in2 {}
1703     set common {}
1704     foreach item $list1 {
1705         if { [lsearch -exact $list2 $item] >= 0 } {
1706             lappend common $item
1707         } else {
1708             lappend in1 $item
1709         }
1710     }
1711     foreach item $list2 {
1712         if { [lsearch -exact $common $item] < 0 } {
1713             lappend in2 $item
1714         }
1715     }
1716     return
1717 }
1718
1719 # procedure to load a file to Tcl string
1720 proc _read_file {filename} {
1721     set fd [open $filename r]
1722     set result [read -nonewline $fd]
1723     close $fd
1724     return $result
1725 }
1726
1727 # procedure to construct name for the mage diff file
1728 proc _diff_img_name {dir1 dir2 casepath imgfile} {
1729     return [file join $dir1 $casepath "diff-[file tail $dir2]-$imgfile"]
1730 }
1731
1732 # auxiliary procedure to produce string comparing two values
1733 proc _diff_show_ratio {value1 value2} {
1734     return "$value1 / $value2 \[[format "%+5.2f%%" [expr 100 * ($value1 - $value2) / double($value2)]]\]"
1735 }
1736
1737 # Procedure to compare results of two runs of test cases
1738 proc _test_diff {dir1 dir2 basename status verbose _logvar {_statvar ""}} {
1739     upvar $_logvar log
1740
1741     # make sure to load diffimage command
1742     uplevel pload VISUALIZATION
1743
1744     # prepare variable (array) for collecting statistics
1745     if { "$_statvar" != "" } {
1746         upvar $_statvar stat
1747     } else {
1748         set stat(cpu1) 0
1749         set stat(cpu2) 0
1750         set stat(mem1) 0
1751         set stat(mem2) 0
1752         set log {}
1753     }
1754
1755     # first check subdirectories
1756     set path1 [file join $dir1 $basename]
1757     set path2 [file join $dir2 $basename]
1758     set list1 [glob -directory $path1 -types d -tails -nocomplain *]
1759     set list2 [glob -directory $path2 -types d -tails -nocomplain *]
1760     if { [llength $list1] >0 || [llength $list2] > 0 } {
1761         _list_diff $list1 $list2 in1 in2 common
1762         if { "$verbose" > 1 } {
1763             if { [llength $in1] > 0 } { _log_and_puts log "Only in $path1: $in1" }
1764             if { [llength $in2] > 0 } { _log_and_puts log "Only in $path2: $in2" }
1765         }
1766         foreach subdir $common {
1767             if { "$verbose" > 2 } {
1768                 _log_and_puts log "Checking [file join $basename $subdir]"
1769             }
1770             _test_diff $dir1 $dir2 [file join $basename $subdir] $status $verbose log stat
1771         }
1772     } else {
1773         # check log files (only if directory has no subdirs)
1774         set list1 [glob -directory $path1 -types f -tails -nocomplain *.log]
1775         set list2 [glob -directory $path2 -types f -tails -nocomplain *.log]
1776         _list_diff $list1 $list2 in1 in2 common
1777         if { "$verbose" > 1 } {
1778             if { [llength $in1] > 0 } { _log_and_puts log "Only in $path1: $in1" }
1779             if { [llength $in2] > 0 } { _log_and_puts log "Only in $path2: $in2" }
1780         }
1781         set gcpu1 0
1782         set gcpu2 0
1783         set gmem1 0
1784         set gmem2 0
1785         foreach logfile $common {
1786             # load two logs
1787             set log1 [_read_file [file join $dir1 $basename $logfile]]
1788             set log2 [_read_file [file join $dir2 $basename $logfile]]
1789             set casename [file rootname $logfile]
1790
1791             # check execution statuses
1792             set status1 UNDEFINED
1793             set status2 UNDEFINED
1794             if { ! [regexp {CASE [^:]*:\s*([\w]+)} $log1 res1 status1] ||
1795                  ! [regexp {CASE [^:]*:\s*([\w]+)} $log2 res2 status2] ||
1796                  "$status1" != "$status2" } {
1797                 _log_and_puts log "STATUS [split $basename /] $casename: $status1 / $status2"
1798
1799                 # if test statuses are different, further comparison makes 
1800                 # no sense unless explicitly requested
1801                 if { "$status" != "all" } {
1802                     continue
1803                 }
1804             }
1805             if { "$status" == "ok" && "$status1" != "OK" } { 
1806                 continue
1807             }
1808
1809             # check CPU times
1810             set cpu1 UNDEFINED
1811             set cpu2 UNDEFINED
1812             if { [regexp {TOTAL CPU TIME:\s*([\d.]+)} $log1 res1 cpu1] &&
1813                  [regexp {TOTAL CPU TIME:\s*([\d.]+)} $log2 res1 cpu2] } {
1814                 set stat(cpu1) [expr $stat(cpu1) + $cpu1]
1815                 set stat(cpu2) [expr $stat(cpu2) + $cpu2]
1816                 set gcpu1 [expr $gcpu1 + $cpu1]
1817                 set gcpu2 [expr $gcpu2 + $cpu2]
1818
1819                 # compare CPU times with 10% precision (but not less 0.5 sec)
1820                 if { [expr abs ($cpu1 - $cpu2) > 0.5 + 0.05 * abs ($cpu1 + $cpu2)] } {
1821                     _log_and_puts log "CPU [split $basename /] $casename: [_diff_show_ratio $cpu1 $cpu2]"
1822                 }
1823             }
1824
1825             # check memory delta
1826             set mem1 UNDEFINED
1827             set mem2 UNDEFINED
1828             if { [regexp {MEMORY DELTA:\s*([\d.]+)} $log1 res1 mem1] &&
1829                  [regexp {MEMORY DELTA:\s*([\d.]+)} $log2 res1 mem2] } {
1830                 set stat(mem1) [expr $stat(mem1) + $mem1]
1831                 set stat(mem2) [expr $stat(mem2) + $mem2]
1832                 set gmem1 [expr $gmem1 + $mem1]
1833                 set gmem2 [expr $gmem2 + $mem2]
1834
1835                 # compare memory usage with 10% precision (but not less 16 KiB)
1836                 if { [expr abs ($mem1 - $mem2) > 16 + 0.05 * abs ($mem1 + $mem2)] } {
1837                     _log_and_puts log "MEMORY [split $basename /] $casename: [_diff_show_ratio $mem1 $mem2]"
1838                 }
1839             }
1840
1841             # check images
1842             set imglist1 [glob -directory $path1 -types f -tails -nocomplain ${casename}.{png,gif} ${casename}-*.{png,gif} ${casename}_*.{png,gif}]
1843             set imglist2 [glob -directory $path2 -types f -tails -nocomplain ${casename}.{png,gif} ${casename}-*.{png,gif} ${casename}_*.{png,gif}]
1844             _list_diff $imglist1 $imglist2 imgin1 imgin2 imgcommon
1845             if { "$verbose" > 1 } {
1846                 if { [llength $imgin1] > 0 } { _log_and_puts log "Only in $path1: $imgin1" }
1847                 if { [llength $imgin2] > 0 } { _log_and_puts log "Only in $path2: $imgin2" }
1848             }
1849             foreach imgfile $imgcommon {
1850 #                if { $verbose > 1 } { _log_and_puts log "Checking [split basename /] $casename: $imgfile" }
1851                 set diffile [_diff_img_name $dir1 $dir2 $basename $imgfile]
1852                 if { [catch {diffimage [file join $dir1 $basename $imgfile] \
1853                                        [file join $dir2 $basename $imgfile] \
1854                                        0 0 0 $diffile} diff] } {
1855                     _log_and_puts log "IMAGE [split $basename /] $casename: $imgfile cannot be compared"
1856                     file delete -force $diffile ;# clean possible previous result of diffimage
1857                 } elseif { $diff != 0 } {
1858                     _log_and_puts log "IMAGE [split $basename /] $casename: $imgfile differs"
1859                 } else {
1860                     file delete -force $diffile ;# clean useless artifact of diffimage
1861                 }
1862             }
1863         }
1864         
1865         # report CPU and memory difference in group if it is greater than 10%
1866         if { [expr abs ($gcpu1 - $gcpu2) > 0.5 + 0.005 * abs ($gcpu1 + $gcpu2)] } {
1867             _log_and_puts log "CPU [split $basename /]: [_diff_show_ratio $gcpu1 $gcpu2]"
1868         }
1869         if { [expr abs ($gmem1 - $gmem2) > 16 + 0.005 * abs ($gmem1 + $gmem2)] } {
1870             _log_and_puts log "MEMORY [split $basename /]: [_diff_show_ratio $gmem1 $gmem2]"
1871         }
1872     }
1873
1874     if { "$_statvar" == "" } {
1875         _log_and_puts log "Total MEMORY difference: [_diff_show_ratio $stat(mem1) $stat(mem2)]"
1876         _log_and_puts log "Total CPU difference: [_diff_show_ratio $stat(cpu1) $stat(cpu2)]"
1877     }
1878 }
1879
1880 # Auxiliary procedure to save log of results comparison to file
1881 proc _log_html_diff {file log dir1 dir2} {
1882     # create missing directories as needed
1883     catch {file mkdir [file dirname $file]}
1884
1885     # try to open a file
1886     if [catch {set fd [open $file w]} res] {
1887         error "Error saving log file $file: $res"
1888     }
1889     
1890     # print header
1891     puts $fd "<html><head><title>Diff $dir1 vs. $dir2</title></head><body>"
1892     puts $fd "<h1>Comparison of test results:</h1>"
1893     puts $fd "<h2>Version A - $dir1</h2>"
1894     puts $fd "<h2>Version B - $dir2</h2>"
1895
1896     # print log body, trying to add HTML links to script files on lines like
1897     # "Executing <filename>..."
1898     puts $fd "<pre>"
1899     set logpath [file split [file normalize $file]]
1900     foreach line $log {
1901         # put a line; highlight considerable (>5%) deviations of CPU and memory
1902         if { [regexp "\[\\\[](\[0-9.e+-]+)%\[\]]" $line res value] && 
1903              [expr abs($value)] > 5 } {
1904             puts $fd "<table><tr><td bgcolor=\"[expr $value > 0 ? \"red\" : \"lightgreen\"]\">$line</td></tr></table>"
1905         } else {
1906             puts $fd $line
1907         }
1908
1909         # add images
1910         if { [regexp {IMAGE[ \t]+([^:]+):[ \t]+([A-Za-z0-9_.-]+)} $line res case img] } {
1911             if { [catch {eval file join "" [lrange $case 0 end-1]} gridpath] } {
1912                # note: special handler for the case if test grid directoried are compared directly
1913                set gridpath ""
1914             }
1915             set img1 "<img src=\"[_make_url $file [file join $dir1 $gridpath $img]]\">"
1916             set img2 "<img src=\"[_make_url $file [file join $dir2 $gridpath $img]]\">"
1917
1918             set difffile [_diff_img_name $dir1 $dir2 $gridpath $img]
1919             if { [file exists $difffile] } {
1920                 set imgd "<img src=\"[_make_url $file $difffile]\">"
1921             } else {
1922                 set imgd "N/A"
1923             }
1924
1925             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>"
1926             puts $fd "<tr><td>$img1</td><td>$img2</td><td>$imgd</td></tr></table>"
1927         }
1928     }
1929     puts $fd "</pre></body></html>"
1930
1931     close $fd
1932     return
1933 }
1934
1935 # get number of CPUs on the system
1936 proc _get_nb_cpus {} {
1937     global tcl_platform env
1938
1939     if { "$tcl_platform(platform)" == "windows" } {
1940         # on Windows, take the value of the environment variable 
1941         if { [info exists env(NUMBER_OF_PROCESSORS)] &&
1942              ! [catch {expr $env(NUMBER_OF_PROCESSORS) > 0} res] && $res >= 0 } {
1943             return $env(NUMBER_OF_PROCESSORS)
1944         }
1945     } elseif { "$tcl_platform(os)" == "Linux" } {
1946         # on Linux, take number of logical processors listed in /proc/cpuinfo
1947         if { [catch {open "/proc/cpuinfo" r} fd] } { 
1948             return 0 ;# should never happen, but...
1949         }
1950         set nb 0
1951         while { [gets $fd line] >= 0 } {
1952             if { [regexp {^processor[ \t]*:} $line] } {
1953                 incr nb
1954             }
1955         }
1956         close $fd
1957         return $nb
1958     } elseif { "$tcl_platform(os)" == "Darwin" } {
1959         # on MacOS X, call sysctl command
1960         if { ! [catch {exec sysctl hw.ncpu} ret] && 
1961              [regexp {^hw[.]ncpu[ \t]*:[ \t]*([0-9]+)} $ret res nb] } {
1962             return $nb
1963         }
1964     }
1965
1966     # if cannot get good value, return 0 as default
1967     return 0
1968 }
1969
1970 # check two files for difference
1971 proc _diff_files {file1 file2} {
1972     set fd1 [open $file1 "r"]
1973     set fd2 [open $file2 "r"]
1974
1975     set differ f
1976     while {! $differ} {
1977         set nb1 [gets $fd1 line1]
1978         set nb2 [gets $fd2 line2]
1979         if { $nb1 != $nb2 } { set differ t; break }
1980         if { $nb1 < 0 } { break }
1981         if { [string compare $line1 $line2] } {
1982             set differ t
1983         }
1984     }
1985
1986     close $fd1
1987     close $fd2
1988
1989     return $differ
1990 }
1991
1992 # Check if file is in DOS encoding.
1993 # This check is done by presence of \r\n combination at the end of the first 
1994 # line (i.e. prior to any other \n symbol).
1995 # Note that presence of non-ascii symbols typically used for recognition
1996 # of binary files is not suitable since some IGES and STEP files contain
1997 # non-ascii symbols.
1998 # Special check is added for PNG files which contain \r\n in the beginning.
1999 proc _check_dos_encoding {file} {
2000     set fd [open $file rb]
2001     set isdos f
2002     if { [gets $fd line] && [regexp {.*\r$} $line] && 
2003          ! [regexp {^.PNG} $line] } {
2004         set isdos t
2005     }
2006     close $fd
2007     return $isdos
2008 }
2009
2010 # procedure to recognize format of a data file by its first symbols (for OCCT 
2011 # BREP and geometry DRAW formats, IGES, and STEP) and extension (all others)
2012 proc _check_file_format {file} {
2013     set fd [open $file rb]
2014     set line [read $fd 1024]
2015     close $fd
2016
2017     set warn f
2018     set ext [file extension $file]
2019     set format unknown
2020     if { [regexp {^DBRep_DrawableShape} $line] } {
2021         set format BREP
2022         if { "$ext" != ".brep" && "$ext" != ".rle" && 
2023              "$ext" != ".draw" && "$ext" != "" } {
2024             set warn t
2025         }
2026     } elseif { [regexp {^DrawTrSurf_} $line] } {
2027         set format DRAW
2028         if { "$ext" != ".rle" && 
2029              "$ext" != ".draw" && "$ext" != "" } {
2030             set warn t
2031         }
2032     } elseif { [regexp {^[ \t]*ISO-10303-21} $line] } {
2033         set format STEP
2034         if { "$ext" != ".step" && "$ext" != ".stp" } {
2035             set warn t
2036         }
2037     } elseif { [regexp {^.\{72\}S[0 ]\{6\}1} $line] } {
2038         set format IGES
2039         if { "$ext" != ".iges" && "$ext" != ".igs" } {
2040             set warn t
2041         }
2042     } elseif { "$ext" == ".igs" } {
2043         set format IGES
2044     } elseif { "$ext" == ".stp" } {
2045         set format STEP
2046     } else {
2047         set format [string toupper [string range $ext 1 end]]
2048     }
2049     
2050     if { $warn } {
2051         puts "$file: Warning: extension ($ext) does not match format ($format)"
2052     }
2053
2054     return $format
2055 }
2056
2057 # procedure to load file knowing its format
2058 proc load_data_file {file format shape} {
2059     switch $format {
2060     BREP { uplevel restore $file $shape }
2061     DRAW { uplevel restore $file $shape }
2062     IGES { pload XSDRAW; uplevel igesbrep $file $shape * }
2063     STEP { pload XSDRAW; uplevel stepread $file __a *; uplevel renamevar __a_1 $shape }
2064     STL  { pload XSDRAW; uplevel readstl $shape $file }
2065     default { error "Cannot read $format file $file" }
2066     }
2067 }
2068
2069 # procedure to get name of temporary directory,
2070 # ensuring it is existing and writeable 
2071 proc _get_temp_dir {} {
2072     global env tcl_platform
2073
2074     # check typical environment variables 
2075     foreach var {TempDir Temp Tmp} {
2076         # check different case
2077         foreach name [list [string toupper $var] $var [string tolower $var]] {
2078             if { [info exists env($name)] && [file isdirectory $env($name)] &&
2079                  [file writable $env($name)] } {
2080                 return [regsub -all {\\} $env($name) /]
2081             }
2082         }
2083     }
2084
2085     # check platform-specific locations
2086     set fallback tmp
2087     if { "$tcl_platform(platform)" == "windows" } {
2088         set paths "c:/TEMP c:/TMP /TEMP /TMP"
2089         if { [info exists env(HOMEDRIVE)] && [info exists env(HOMEPATH)] } {
2090             set fallback [regsub -all {\\} "$env(HOMEDRIVE)$(HOMEPATH)/tmp" /]
2091         }
2092     } else {
2093         set paths "/tmp /var/tmp /usr/tmp"
2094         if { [info exists env(HOME)] } {
2095             set fallback "$env(HOME)/tmp"
2096         }
2097     }
2098     foreach dir $paths {
2099         if { [file isdirectory $dir] && [file writable $dir] } {
2100             return $dir
2101         }
2102     }
2103
2104     # fallback case: use subdir /tmp of home or current dir
2105     file mkdir $fallback
2106     return $fallback
2107 }
2108
2109 # extract of code from testgrid command used to process jobs running in 
2110 # parallel until number of jobs in the queue becomes equal or less than 
2111 # specified value
2112 proc _testgrid_process_jobs {worker {nb_ok 0}} {
2113     # bind local vars to variables of the caller procedure
2114     upvar log log
2115     upvar logdir logdir
2116     upvar job_def job_def
2117     upvar nbpooled nbpooled
2118     upvar userbreak userbreak
2119     upvar refresh refresh
2120     upvar refresh_timer refresh_timer
2121
2122     catch {tpool::resume $worker}
2123     while { ! $userbreak && $nbpooled > $nb_ok } {
2124         foreach job [tpool::wait $worker [array names job_def]] {
2125             eval _log_test_case \[tpool::get $worker $job\] $job_def($job) log
2126             unset job_def($job)
2127             incr nbpooled -1
2128         }
2129
2130         # check for user break
2131         if { "[info commands dbreak]" == "dbreak" && [catch dbreak] } {
2132             set userbreak 1
2133         }
2134
2135         # update summary log with requested period
2136         if { $logdir != "" && $refresh > 0 && [clock seconds] > $refresh_timer + $refresh } {
2137             _log_summarize $logdir $log
2138             set refresh_timer [clock seconds]
2139         }
2140     }
2141     catch {tpool::suspend $worker}
2142 }
2143
2144 help checkcolor {
2145   Check pixel color.
2146   Use: checkcolor x y red green blue
2147   x y - pixel coordinates
2148   red green blue - expected pixel color (values from 0 to 1)
2149   Function check color with tolerance (5x5 area)
2150 }
2151 # Procedure to check color using command vreadpixel with tolerance
2152 proc checkcolor { coord_x coord_y rd_get gr_get bl_get } {
2153     puts "Coordinate x = $coord_x"
2154     puts "Coordinate y = $coord_y"
2155     puts "RED color of RGB is $rd_get"
2156     puts "GREEN color of RGB is $gr_get"
2157     puts "BLUE color of RGB is $bl_get"
2158
2159     if { $coord_x <= 1 || $coord_y <= 1 } {
2160       puts "Error : minimal coordinate is x = 2, y = 2. But we have x = $coord_x y = $coord_y"
2161       return -1
2162     }
2163
2164     set color ""
2165     catch { [set color "[vreadpixel ${coord_x} ${coord_y} rgb]"] }
2166     if {"$color" == ""} {
2167       puts "Error : Pixel coordinates (${position_x}; ${position_y}) are out of view"
2168     }
2169     set rd [lindex $color 0]
2170     set gr [lindex $color 1]
2171     set bl [lindex $color 2]
2172     set rd_int [expr int($rd * 1.e+05)]
2173     set gr_int [expr int($gr * 1.e+05)]
2174     set bl_int [expr int($bl * 1.e+05)]
2175     set rd_ch [expr int($rd_get * 1.e+05)]
2176     set gr_ch [expr int($gr_get * 1.e+05)]
2177     set bl_ch [expr int($bl_get * 1.e+05)]
2178
2179     if { $rd_ch != 0 } {
2180       set tol_rd [expr abs($rd_ch - $rd_int)/$rd_ch]
2181     } else {
2182       set tol_rd $rd_int
2183     }
2184     if { $gr_ch != 0 } {
2185       set tol_gr [expr abs($gr_ch - $gr_int)/$gr_ch]
2186     } else {
2187       set tol_gr $gr_int
2188     }
2189     if { $bl_ch != 0 } {
2190       set tol_bl [expr abs($bl_ch - $bl_int)/$bl_ch]
2191     } else {
2192       set tol_bl $bl_int
2193     }
2194
2195     set status 0
2196     if { $tol_rd > 0.2 } {
2197       puts "Warning : RED light of additive color model RGB is invalid"
2198       set status 1
2199     }
2200     if { $tol_gr > 0.2 } {
2201       puts "Warning : GREEN light of additive color model RGB is invalid"
2202       set status 1
2203     }
2204     if { $tol_bl > 0.2 } {
2205       puts "Warning : BLUE light of additive color model RGB is invalid"
2206       set status 1
2207     }
2208
2209     if { $status != 0 } {
2210       puts "Warning : Colors of default coordinate are not equal"
2211     }
2212
2213     global stat
2214     if { $tol_rd > 0.2 || $tol_gr > 0.2 || $tol_bl > 0.2 } {
2215       set info [_checkpoint $coord_x $coord_y $rd_ch $gr_ch $bl_ch]
2216       set stat [lindex $info end]
2217       if { ${stat} != 1 } {
2218           puts "Error : Colors are not equal in default coordinate and in the near coordinates too"
2219           return $stat
2220       } else {
2221           puts "Point with valid color was found"
2222           return $stat
2223       }
2224     } else {
2225       set stat 1
2226     }
2227 }
2228
2229 # Procedure to check color in the point near default coordinate
2230 proc _checkpoint {coord_x coord_y rd_ch gr_ch bl_ch} {
2231     set x_start [expr ${coord_x} - 2]
2232     set y_start [expr ${coord_y} - 2]
2233     set mistake 0
2234     set i 0
2235     while { $mistake != 1 && $i <= 5 } {
2236       set j 0
2237       while { $mistake != 1 && $j <= 5 } {
2238           set position_x [expr ${x_start} + $j]
2239           set position_y [expr ${y_start} + $i]
2240           puts $position_x
2241           puts $position_y
2242
2243           set color ""
2244           catch { [set color "[vreadpixel ${position_x} ${position_y} rgb]"] }
2245           if {"$color" == ""} {
2246             puts "Warning : Pixel coordinates (${position_x}; ${position_y}) are out of view"
2247             incr j
2248             continue
2249           }
2250           set rd [lindex $color 0]
2251           set gr [lindex $color 1]
2252           set bl [lindex $color 2]
2253           set rd_int [expr int($rd * 1.e+05)]
2254           set gr_int [expr int($gr * 1.e+05)]
2255           set bl_int [expr int($bl * 1.e+05)]
2256
2257           if { $rd_ch != 0 } {
2258             set tol_rd [expr abs($rd_ch - $rd_int)/$rd_ch]
2259           } else {
2260             set tol_rd $rd_int
2261           }
2262           if { $gr_ch != 0 } {
2263             set tol_gr [expr abs($gr_ch - $gr_int)/$gr_ch]
2264           } else {
2265             set tol_gr $gr_int
2266           }
2267           if { $bl_ch != 0 } {
2268             set tol_bl [expr abs($bl_ch - $bl_int)/$bl_ch]
2269           } else {
2270             set tol_bl $bl_int
2271           }
2272
2273           if { $tol_rd > 0.2 || $tol_gr > 0.2 || $tol_bl > 0.2 } {
2274             puts "Warning : Point with true color was not found near default coordinates"
2275             set mistake 0
2276           } else {
2277             set mistake 1
2278           }
2279           incr j
2280       }
2281       incr i
2282     }
2283     return $mistake
2284 }