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