chiark / gitweb /
5079defd1d00abfbc9995a6f439f21efe95758ba
[ypp-sc-tools.db-test.git] / pctb / dictionary-manager
1 #!/usr/bin/wish
2
3 # helper program for OCR in PCTB upload client
4
5 # This is part of ypp-sc-tools, a set of third-party tools for assisting
6 # players of Yohoho Puzzle Pirates.
7 #
8 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
9 #
10 # This program is free software: you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation, either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 #
23 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
24 # are used without permission.  This program is not endorsed or
25 # sponsored by Three Rings.
26
27
28 # ./dictionary-manager --approve-updates ijackson@login.chiark.greenend.org.uk /home/ijackson/things/ypp-sc-tools.pctb-dict-test/pctb /home/ftp/users/ijackson/pctb/test
29 # ./dictionary-manager --approve-updates ijackson@login.chiark.greenend.org.uk /home/ijackson/things/ypp-sc-tools.pctb-dict/pctb /home/ftp/users/ijackson/pctb
30
31 # ./dictionary-manager --approve-updates '' . .
32
33
34 # invocation:
35 # OUT OF DATE
36 #  run this without args
37 #  then on stdin write
38 #     one line which is a Tcl list for unk_{l,r} unk_contexts glyphsdone etc.
39 #     the xpm in the format expected
40 #  then expect child to exit 0, or write a single 0 byte to fd 4
41 #  if it wrote a byte to fd 4, it can take another question
42
43
44 #---------- library routines ----------
45
46 proc manyset {list args} {
47     foreach val $list var $args {
48         upvar 1 $var my
49         set my $val
50     }
51 }
52
53 proc must_gets {f lvar} {
54     upvar 1 $lvar l
55     if {[gets $f l] < 0} { error "huh?" }
56 }
57
58 proc must_gets_imagel {f lvar} {
59     global debug_rect
60     upvar 1 $lvar l
61     must_gets $f l
62     if {$debug_rect} { debug "<< $l" }
63 }
64
65 proc must_gets_exactly {f expected} {
66     must_gets $f got
67     if {[string compare $expected $got]} { error "$expected $got ?" }
68 }
69
70 proc read_counted {f var} {
71     upvar 1 $var val
72     must_gets $f count
73     set val [read $f $count]
74     must_gets $f eol
75     if {[string length $eol]} { error "$eol ?" }
76     debug "READ_COUNTED $count $var"
77 }
78
79 proc puts_counted {f dvar} {
80     upvar 1 $dvar d
81     set count [string length $d]
82     puts $f $count
83     puts $f $d
84     debug "PUTS_COUNTED $count $dvar"
85 }
86
87 proc bgerror {m} {
88     global errorCode errorInfo
89     puts stderr "ERROR: $m\n[list $errorCode]\n$errorInfo\n";
90     exit 16
91 }
92
93 #---------- display core ----------
94
95 set mul 6
96 set inter 1
97
98 set gotsh 20
99 set csrh 20
100 set ctxh 20
101
102 proc init_widgets {} {
103     # idempotent
104     global csrh gotsh ctxh
105
106     if {[winfo exists .d]} return
107
108     frame .privacy -bd 2 -relief groove
109     pack .privacy -side top -padx 2 -pady 2 -fill x
110
111     upload_init
112     
113     frame .d -pady 2 -padx 2 -bg black -bd 2 -relief sunken
114
115     image create bitmap image/main
116     label .d.mi -image image/main -bd 0
117
118     frame .d.csr -bg black -height $csrh
119     frame .d.got -bg black -height $gotsh
120     frame .d.ctx -bg black
121
122     image create bitmap image/cursor -foreground white -background black \
123         -data \
124 {#define csr_width 11
125 #define csr_height 11
126 static unsigned char csr_bits[] = {
127    0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x21, 0x04, 0x22, 0x02, 0x25, 0x05,
128    0xaa, 0x02, 0x74, 0x01, 0xa8, 0x00, 0x70, 0x00, 0x20, 0x00};
129 }
130
131     frame .d.csr.csr
132     label .d.csr.csr.l -image image/cursor -compound left -fg white -bg black
133     entry .d.csr.csr.e -bd 0
134     pack .d.csr.csr.l -side left
135
136     frame .selctx -bd 2 -relief groove
137     frame .d.mi.csr_0 -bg white -width 1
138     frame .d.mi.csr_1 -bg white -width 1
139     frame .pe
140     frame .pe.grid
141
142     button .pe.ok -text OK
143     pack .pe.grid .pe.ok -side left
144
145     pack .d.mi .d.ctx -side top -anchor w
146     pack .d -fill x -padx 2 -pady 2
147
148     frame .help -bd 2 -relief groove
149     pack .help -pady 2 -padx 2
150 }
151
152 proc resize_widgets_core {} {
153     global mulcols mulrows csrh gotsh ctxh
154     global unk_l unk_contexts
155     
156     foreach w {.d.csr .d.got .d.ctx} {
157         $w configure -width $mulcols
158     }
159     .d.csr configure -width [expr {$mulcols+150}]
160
161     eval destroy [winfo children .d.ctx]
162 }
163
164 set last_ht {}
165
166 proc helptext {t} {
167     global last_ht
168     if {![string compare $t $last_ht]} return
169     eval destroy [grid slaves .help]
170     set y 0; foreach l $t {
171         set x 0; foreach c $l {
172             set w .help.at${x}x${y}
173             label $w -text $c
174             grid $w -row $y -column $x -padx 5 -sticky w
175             incr x
176         }
177         incr y
178     }
179     set last_ht $t
180 }
181
182 proc bind_key {k proc} {
183     global keybindings
184     bind .d <Key-$k> $proc
185     set keybindings($k) [expr {!![string length $proc]}]
186     .d configure -takefocus 1
187 }
188 proc unbind_all_keys {} {
189     global keybindings
190     foreach k [array names keybindings] { bind_key $k {} }
191     .d configure -takefocus 0
192 }
193
194 #---------- database read and write common wrapper ----------
195
196 proc db_getsl {f} {
197     if {[gets $f l] < 0} { error "unexpected db eof" }
198     return $l
199 }
200
201 proc read_database {fn} {
202     global reqkind database database_fn
203     upvar #0 database_magic/$reqkind magic
204     catch { unset database }
205
206     set database_fn $fn
207     if {![file exists $database_fn]} return
208     set f [open $database_fn r]
209     if {[string compare [db_getsl $f] $magic]} { error "$magic $reqkind ?" }
210
211     read_database_header/$reqkind $f
212     while 1 {
213         set l1 [db_getsl $f]
214     
215         if {![string length $l1]} continue
216         if {[regexp {^\#} $l1]} continue
217         if {![string compare . $l1]} break
218
219         read_database_entry/$reqkind $f $l1
220     }
221     close $f
222 }
223
224 proc write_database {} {
225     global reqkind database_fn database
226     upvar #0 database_magic/$reqkind magic
227     
228     set f [open $database_fn.tmp w]
229     puts $f $magic
230
231     write_database_header/$reqkind $f
232
233     set ol {}
234     foreach bm [array names database] {
235         lappend ol [format_database_entry/$reqkind $bm $database($bm)]
236     }
237     foreach o [lsort $ol] {
238         puts $f $o
239     }
240     puts $f "."
241     close $f
242     file rename -force $database_fn.tmp $database_fn
243 }
244
245 proc select_database {dbname_spec} {
246     global dbname
247     set dbname $dbname_spec
248     read_database "./#local-$dbname#.txt"
249 }
250
251 proc do_database_update {im def} {
252     global database
253     maybe_upload_entry $im $def
254     set database($im) $def
255     write_database
256 }
257     
258 proc required/char {} {
259     global mulrows glyphsdone unk_l unk_r unk_contexts rows new_context
260     global all_contexts debug_rect
261     
262     must_gets stdin l
263     debug "GOT $l"
264
265     manyset [lrange $l 0 3] unk_l unk_r unk_contexts
266     set glyphsdone [lrange $l 3 end]
267
268     char_read_pgm stdin
269
270     catch { unset all_contexts }
271
272     resize_widgets_core
273     foreach w {0 1} {
274         .d.mi.csr_$w configure -height $mulrows
275     }
276     set maxh 0
277     foreach {min max context contexts got} $glyphsdone {
278         show_context maxh $min $context
279         foreach ctx $contexts { set all_contexts($ctx) 1 }
280     }
281     foreach ctx $unk_contexts { set all_contexts($ctx) 1 }
282
283     eval destroy [winfo children .selctx]
284     label .selctx.title -text \
285         {Select match context for altering dictionary:}
286     pack .selctx.title -side left
287     set new_context [lindex $unk_contexts 0]
288
289     set ci 0; foreach ctx [lsort [array names all_contexts]] {
290         set all_contexts($ctx) $ci
291         set selw .selctx.c$ci
292         set seltxt $ctx
293         radiobutton $selw -variable new_context -value $ctx -text $seltxt
294         pack $selw -side left
295         incr ci
296     }
297     $selw configure -text "$seltxt."
298     label .selctx.warning -text {See README.charset.}
299     pack .selctx.warning -side left
300
301     show_context maxh $unk_l $unk_contexts
302     .d.ctx configure -height $maxh
303     pack forget .pe
304     pack .selctx -before .d -padx 2 -fill x
305     pack .d.csr -side top -before .d.mi -anchor w
306     pack .d.got .d.ctx -side top -after .d.mi -anchor w
307     pack configure .selctx -fill x
308     focus .d
309
310     select_database char$rows
311     draw_glyphsdone
312     startup_cursor
313 }
314
315 proc approve_showentry_xinfo/char {w def} {
316     set unic [string2unicodenames $def]
317     label $w -text $unic
318 }
319
320 #========== PIXMAPS ==========
321
322 #---------- pixmap database read and write ----------
323
324 set database_magic/pixmap {# ypp-sc-tools pctb pixmaps v1}
325
326 proc read_database_header/pixmap {f} { }
327 proc read_database_entry/pixmap {f def} {
328     global database
329
330     set im ""
331     
332     set p3 [db_getsl $f];       append im $p3    "\n"
333     if {[string compare $p3 P3]} { error "$p3 ?" }
334
335     set wh [db_getsl $f];       append im $wh    "\n";   manyset $wh w h
336     set depth [db_getsl $f];    append im $depth "\n"
337
338     for {set y 0} {$y < $h} {incr y} {
339         set line [db_getsl $f]; append im $line  "\n"
340     }
341     set database($im) $def
342 }
343 proc write_database_header/pixmap {f} { puts $f "" }
344 proc format_database_entry/pixmap {im def} {
345     return "$def\n$im"
346 }
347
348 #---------- pixmap display and input handling ----------
349
350 proc foreach_pixmap_col {var body} {
351     global alloptions
352     upvar 1 $var col
353     for {set col 0} {$col < [llength $alloptions]/3} {incr col} {
354         uplevel 1 $body
355     }
356 }
357
358 proc pixmap_select {ncol} {
359     global alloptions
360     debug "PIX SELECT $ncol [llength $alloptions]"
361     foreach_pixmap_col col {
362         if {$col==$ncol} continue
363         .pe.grid.l$col selection clear 0 end
364     }
365     pixmap_maybe_ok
366 }
367 proc pixmap_maybe_ok {} {
368     global alloptions pixmap_selcol pixmap_selrow
369     set nsel 0
370     foreach_pixmap_col col {
371         set cs [.pe.grid.l$col curselection]
372         set lcs [llength $cs]
373         if {!$lcs} continue
374         incr nsel $lcs
375         set pixmap_selcol $col
376         set pixmap_selrow [lindex $cs 0]
377     }
378     if {$nsel==1} {
379         debug "MAYBE_OK YES col=$pixmap_selcol row=$pixmap_selrow."
380         .pe.ok configure -state normal -command pixmap_ok
381     } else {
382         .pe.ok configure -state disabled -command {}
383     }
384 }
385 proc pixmap_ok {} {
386     global database ppm pixmap_selcol pixmap_selrow mainkind alloptions
387
388     return_result_start
389     foreach_pixmap_col col {
390         .pe.grid.l$col configure -state disabled
391     }
392     .pe.ok configure -state disabled
393
394     manyset [lrange $alloptions [expr {$pixmap_selcol*3}] end] \
395         colname coldesc rows
396     manyset [lrange $rows [expr {$pixmap_selrow*2}] end] \
397         rowname rowdesc
398     set result "$colname - $rowname"
399     debug "UPDATE PIXMAP AS >$result<"
400
401     do_database_update $ppm $result
402
403     return_result_finish
404 }
405
406 proc required/pixmap {} {
407     global unk_what ppm mulcols alloptions
408     must_gets stdin unk_what
409     debug "GOT pixmap $unk_what"
410     set ppm {}
411     while 1 {
412         must_gets_imagel stdin ppml
413         if {![string length $ppml]} break
414         append ppm $ppml "\n"
415     }
416     set data [exec pnmscale 2 << $ppm]
417     image create photo image/main -data $data
418
419     set alloptions [exec ./database-info-fetch $unk_what]
420
421     select_database pixmap
422
423     set mulcols [image width image/main]
424     set mulrows [image height image/main]
425     resize_widgets_core
426     place forget .d.mi.csr_0
427     place forget .d.mi.csr_1
428
429     pack forget .selctx .d.csr .d.got
430     pack .pe -side top -before .d -pady 2
431     .d configure -takefocus 0
432     #-pady 2 -fill x
433
434     eval destroy [winfo children .pe.grid]
435     set col 0; foreach {colname coldesc rows} $alloptions {
436         debug "INIT $col $colname \"$coldesc\""
437         label .pe.grid.t$col -text $colname
438         listbox .pe.grid.l$col
439         foreach {rowname rowdesc} $rows {
440             debug "INIT $col $colname \"$coldesc\" $rowname \"$rowdesc\""
441             .pe.grid.l$col insert end $rowdesc
442         }
443         bind .pe.grid.l$col <<ListboxSelect>> [list pixmap_select $col]
444         grid .pe.grid.t$col -column $col -row 0
445         grid .pe.grid.l$col -column $col -row 1
446         incr col
447     }
448     pixmap_maybe_ok
449     
450     helptext {
451         {{Indicate the meaning of this image, and click OK.}}
452     }
453 }
454
455 proc approve_showentry_xinfo/pixmap {w def} {
456     label $w -image image/empty
457 }
458
459 #========== UPLOADS TO DICTIONARY SERVER ==========
460
461 proc upload_init {} {
462     global privacy_setting
463
464     set privacy_setting [upload_status]
465
466     label .privacy.warn -text " Privacy "
467     if {$privacy_setting} {
468         .privacy.warn configure -background yellow -foreground black
469     }
470     label .privacy.overall -text " Upload new dictionary entry:"
471     label .privacy.reference -text " See README.privacy."
472
473     pack .privacy.warn .privacy.overall -side left
474
475     foreach {setting string} {
476         0 {No}
477         1 {Yes, anonymously}
478         2 {Yes, quoting my pirate name.}
479     } {
480         radiobutton .privacy.o$setting -text $string \
481             -value $setting -variable privacy_setting
482         pack .privacy.o$setting -side left
483         if {$setting > $privacy_setting} {
484             .privacy.o$setting configure -state disabled
485         }
486     }
487     pack .privacy.reference -side left
488
489     if {!$privacy_setting} {
490         foreach w [winfo children .privacy] {
491             $w configure -state disabled
492         }
493     }
494     if {$privacy_setting} {
495         package require http
496         ::http::config -urlencoding utf-8
497     }
498 }
499
500 proc upload_status {} {
501     # returns 0, 1, 2 for none, anon, with pirate name
502     global env
503
504     if {![info exists env(YPPSC_PCTB_DICT_SUBMIT)]} { debug a; return 0 }
505     if {![string compare 0 $env(YPPSC_PCTB_DICT_SUBMIT)]} { debug b; return 0 }
506
507     if {![info exists env(YPPSC_PIRATE)]} { return 1 }
508     if {![info exists env(YPPSC_OCEAN)]} { return 1 }
509     if {![string length $env(YPPSC_PIRATE)]} { return 1 }
510     if {![string length $env(YPPSC_OCEAN)]} { return 1 }
511
512     return 2
513 }
514
515 proc maybe_upload_entry {im def} {
516     global reqkind privacy_setting env dbname quiet
517
518     debug "DB-UPDATE PRIVACY $privacy_setting"
519     if {!$privacy_setting} return
520
521     debug "DB-UPDATE UPLOADING"
522
523     set pl {}
524     lappend pl dict $dbname
525
526     if {$privacy_setting>=2} {
527         set pirate [string totitle $env(YPPSC_PIRATE)]
528         set ocean [string totitle $env(YPPSC_OCEAN)]
529         debug "DB-UPDATE NON-ANON $ocean $pirate"
530         lappend pl \
531             pirate $pirate \
532             ocean $ocean
533     }
534     lappend pl entry [format_database_entry/$reqkind $im $def]
535
536     set url $env(YPPSC_PCTB_DICT_SUBMIT)
537     append url dictionary-update-receiver
538
539     set query [eval ::http::formatQuery $pl]
540     regsub -all {%0d} $query {} query
541     debug "DB-UPDATE QUERY $query"
542
543     if {[regexp {^\.?/} $url]} {
544         set cmd [list $url $query]
545         debug "SUBMIT CMD [string range $cmd 0 200]..."
546         set body [eval exec $cmd 2>@ stderr]
547         regsub {^Content-Type: text/plain.*\n\n} $body {} body
548     } else {
549
550         if {[catch {
551             set req [::http::geturl $url -query $query]
552         } emsg]} {
553             puts stderr \
554                 "\nWARNING: Cannot do dictionary upload: $emsg\n"
555             return
556         }
557         upvar #0 $req s
558         debug "DB-UPDATE DONE $req $s(status) [array names s]"
559         set ncode [::http::ncode $req]
560
561         if {!(![string compare ok $s(status)] &&
562               ![string compare 200 $ncode])} {
563             set m "\nWARNING: Dictionary upload failed:"
564             foreach v {status http error posterror} {
565                 if {[info exists s($v)]} { append m "\n $v: $s($v)" }
566             }
567             puts stderr $m
568             return
569         }
570         set body $s(body)
571         ::http::cleanup $req
572     }
573
574     if {![string match {OK *} $body]} {
575         set m "\nWARNING: Dictionary upload went wrong:\n"
576         append m "\n  " [join [split $body "\n"] "\n  "]
577         puts stderr $m
578         return
579     }
580
581     if {!$quiet} {
582         puts stderr \
583             "Uploaded $dbname `$def': $body"
584     }
585 }
586
587 #========== CHARACTER SET ==========
588
589 #---------- pgm input processor ----------
590
591 proc char_read_pgm {f} {
592     global glyphsdone mul inter rhsmost_max unk_l unk_r mulcols mulrows
593     global cols rows charkey
594     
595     must_gets_imagel $f l
596     if {[string compare $l P2]} { error "magic $l ?" }
597
598     must_gets_imagel $f l
599     if {![regexp {^([1-9]\d{0,3}) ([1-9]\d{0,3}) ([1-9]\d?)$} \
600               $l dummy cols rows maxval]} { error "head $l ?" }
601
602     for {set depth 1} {$maxval != (1<<$depth)-1} {incr depth} {
603         if {$depth >= 16} { error "maxval $maxval ?" }
604     }
605
606     set chop_l [expr {$unk_l - 80}]
607     set chop_r [expr {$cols - $unk_l - 100}]
608     if {$chop_l<0} { set chop_l 0 }
609     if {$chop_r<0} { set chop_r 0 }
610
611     set unk_l [expr {$unk_l - $chop_l}]
612     set unk_r [expr {$unk_r - $chop_l}]
613     set ngd {}
614     foreach {min max context contexts got} $glyphsdone {
615         lappend ngd \
616             [expr {$min-$chop_l}] \
617             [expr {$max-$chop_l}] \
618             $context $contexts $got
619     }
620     set glyphsdone $ngd
621
622     set realcols $cols
623     set cols [expr {$cols - $chop_l - $chop_r}]
624     debug "NOW cols=$cols chop_l,r=$chop_l,$chop_r rows=$rows\
625                 $unk_l $unk_r $ngd"
626
627     set mulcols [expr {$cols*$mul+$inter}]
628     set mulrows [expr {$rows*$mul+$inter}]
629
630     set o "P3\n$mulcols $mulrows 15\n"
631
632     for {set x 0} {$x<$cols} {incr x} { set charkey($x) {} }
633
634     set ointer1 "   1  1  1"
635     set ointer  [string repeat $ointer1 $inter]
636     set ointerl "[string repeat $ointer1 $mulcols]\n"
637
638     append o $ointerl
639     
640     for {set y 0} {$y<$rows} {incr y} {
641         must_gets_imagel $f l
642         if {[llength $l] != $realcols} { error "realcols=$realcols $l ?" }
643
644         set ol $ointer
645
646         for {set x 0} {$x<$cols} {incr x} {
647             set realx [expr {$x + $chop_l}]
648             set c [lindex $l $realx]
649             append charkey($x) [format %x $c]
650
651             set how "u"
652             if {$x >= $unk_l && $x <= $unk_r} {
653                 set how q
654             } else {
655                 set ab 0
656                 foreach {min max context contexts got} $glyphsdone {
657                     set rhsmost_max $max
658                     if {$x >= $min && $x <= $max} {
659                         set how [lindex {a b} $ab]
660                         break
661                     }
662                     set ab [expr {!$ab}]
663                 }
664             }
665             set c15 [expr {$c << (16-$depth)}]
666             set c15 [expr {$c15 | ($c15 >> $depth)}]
667             set c15 [expr {$c15 | ($c15 >> $depth*2)}]
668             set c15 [expr {$c15 >> 12}]
669
670             foreach rgb {r g b} { set $rgb {$c15} }
671             switch -exact $how {
672                 a { set r {$c15>>1 | 0x8} }
673                 b { set b {$c15>>2 | 0xc} }
674                 u { set b  0              }
675                 q { set b  0              }
676                 default { error "how $how ?" }
677             }
678 #debug "PIXEL $x,$y how=$how c=$c c15=$c15 $r $g $b"
679
680             set opixel " "
681             foreach rgb {r g b} {
682                 append opixel [format " %2d" [expr [set $rgb]]]
683             }
684             append ol [string repeat $opixel [expr {$mul-$inter}]]
685             append ol $ointer
686         }
687         append ol "\n"
688         append o [string repeat $ol [expr {$mul-$inter}]]
689         append o $ointerl
690     }
691
692 #    debug "DATA $o"
693     set data [exec pnmscale 1 << $o]
694     image create photo image/main -data $data
695 }
696
697 #---------- character set editor display ----------
698
699 proc show_context {maxhv x ctxs} {
700     global mul
701     upvar 1 $maxhv maxh
702     set w .d.ctx.at$x
703     if {[llength $ctxs]==1} { set fg blue } { set fg yellow }
704     label $w -bg black -fg $fg -text [join $ctxs "/\n"] -justify left
705     place $w -x [expr {($x-1)*$mul}] -y 0
706     set wh [winfo reqheight $w]
707     if {$wh > $maxh} { set maxh $wh }
708 }
709
710 proc draw_glyphsdone {} {
711     global glyphsdone mul inter
712     eval destroy [winfo children .d.got]
713     foreach {min max context contexts got} $glyphsdone {
714         frame .d.got.m$min -bd 0 -background \#888
715         label .d.got.m$min.l -text "$got" -fg white -bg black -bd 0
716         pack .d.got.m$min.l -padx 1 -pady 1
717         place .d.got.m$min -x [expr {$min*$mul+$inter}] -y 0
718     }
719 }
720
721 proc startup_cursor {} {
722     global cur_already cur_mode cur_0 cur_1 last_ht
723     global glyphsdone unk_l unk_r
724     
725     set cur_already [expr {[llength $glyphsdone]/5-1}]
726     set cur_mode 1 ;# one of:   0 1 already text
727
728     set cur_0 $unk_l
729     set cur_1 [expr {$unk_r+1}]
730
731     recursor
732 }
733
734 #---------- character set runtime display and keystroke handling ----------
735
736 proc char_exactly_selctxts {contexts} {
737     global all_contexts
738     foreach ctx [array names all_contexts] {
739         set ci $all_contexts($ctx)
740         set selw .selctx.c$ci
741         if {[lsearch -exact $contexts $ctx]>=0} {
742             set state normal
743         } else {
744             set state disabled
745         }
746         $selw configure -state $state
747     }
748 }
749
750 proc recursor/0 {} { recursor//01 0 }
751 proc recursor/1 {} { recursor//01 1 }
752 proc recursor//01 {z1} {
753     global mul rhsmost_max cols glyphsdone cur_0 cur_1
754     global all_contexts
755     upvar #0 cur_$z1 cur
756     .d.csr.csr.l configure -text "adjust [char_get_definition_context_actual]"
757     place .d.csr.csr -x [expr {$cur*$mul - 7}]
758
759     set okctxts [char_get_definition_contexts]
760     char_exactly_selctxts $okctxts
761
762     foreach ctx [lsort [array names all_contexts]] {
763         set key [string range $ctx 0 0]
764         if {[lsearch -exact $okctxts $ctx] >= 0} {
765             bind_key [string tolower $key] "
766                 [list set new_context $ctx]
767                 recursor
768             "
769         } else {
770             bind_key [string tolower $key] {}
771         }
772         lappend context_help $key
773     }
774     set context_help [list [join $context_help " "] \
775                           {Set match context for new glyph.}]
776
777     bind_key space { othercursor }
778     bind_leftright_q cur_$z1 0 [expr {$cols-1}]
779     if {[llength $glyphsdone]} {
780         bind_key BackSpace { set cur_mode already; recursor }
781     } else {
782         bind_key BackSpace {}
783     }
784     bind_key Return {
785         char_start_define_text
786     }
787     helptext [list                                              \
788         {{<- ->}   {move cursor, adjusting area to define}}     \
789         {Space     {switch to moving other cursor}}             \
790         {Return    {confirm location, enter letter(s)}}         \
791         {Backspace {switch to correcting earlier ocr}}          \
792         {Q         {quit and abandon OCR run}}                  \
793         $context_help                                           \
794                   ]
795 }
796 proc othercursor {} {
797     global cur_mode
798     set cur_mode [expr {!$cur_mode}]
799     recursor
800 }
801
802 proc char_start_define_text {} {
803     global cur_0 cur_1 cur_mode
804     if {$cur_0 == $cur_1} return
805     set cdgdca [char_get_definition_context_actual]
806     if {![string length $cdgdca]} return
807     .d.csr.csr.e delete 0 end
808     set cur_mode text
809     .d.csr.csr.l configure -text "define $cdgdca:"
810     recursor
811 }
812
813 proc recursor/text {} {
814     global all_contexts
815     
816     helptext {
817         {Return   {confirm entry of new glyph}}
818         {Escape   {abandon entry}}
819     }
820     unbind_all_keys
821     pack .d.csr.csr.e -side left -padx 2
822     focus .d.csr.csr.e
823     bind .d.csr.csr.e <Key-Return> {
824         set strq [.d.csr.csr.e get]
825         if {[string length $strq]} {
826             RETURN_RESULT DEFINE [list $strq]
827         }
828     }
829     bind .d.csr.csr.e <Key-Escape> {
830         bind_key Escape {}
831         pack forget .d.csr.csr.e
832         set cur_mode 1
833         focus .d
834         recursor
835     }
836 }
837
838 proc recursor/already {} {
839     global mul
840     global cur_already mul
841     global glyphsdone cur_already mul
842
843     char_exactly_selctxts [lindex $glyphsdone [expr {$cur_already*5+2}]]
844
845     .d.csr.csr.l configure -text {correct}
846     set rmax [lindex $glyphsdone [expr {$cur_already*5}]]
847     place .d.csr.csr -x [expr {$rmax*$mul-3}]
848     bind_key Return {}
849     bind_leftright_q cur_already 0 [expr {[llength $glyphsdone]/5-1}]
850     bind_key space { bind_key Delete {}; set cur_mode 1; recursor }
851     bind_key Delete {
852         RETURN_RESULT DELETE [lrange $glyphsdone \
853                                   [expr $cur_already*5] \
854                                   [expr $cur_already*5+2]]
855     }
856     helptext {
857         {{<- ->}   {move cursor, selecting glyph to correct}}
858         {Del       {clear this glyph from the recognition database}}
859         {Space     {switch to selecting area to define as new glyph}}
860         {Q         {quit and abandon OCR run}}
861     }
862 }
863
864 proc bind_leftright_q {var min max} {
865     bind_key Left  [list leftright $var $min $max -1]
866     bind_key Right [list leftright $var $min $max +1]
867     bind_key q     {
868         puts stderr "\nCharacter resolver quitting as you requested."
869         exit 1
870     }
871 }
872 proc leftright {var min max inc} {
873     upvar #0 $var v
874     set vnew $v
875     incr vnew $inc
876     if {$vnew < $min || $vnew > $max} return
877     set v $vnew
878     recursor
879 }
880
881 proc recursor {} {
882     global csrh cur_mode cur_0 cur_1 mul
883     foreach z1 {0 1} {
884         place .d.mi.csr_$z1 -y 0 -x [expr {[set cur_$z1] * $mul}]
885     }
886     recursor/$cur_mode
887 }
888
889 #---------- character database read and write ----------
890
891 # OUT OF DATE
892 # database format:
893 # series of glyphs:
894 #   <context> <ncharacters> <hex>...
895 #   width
896 #   <hex-bitmap>
897
898 # $database($context 0x<bits> 0x<bits>...) = $hex
899
900 set database_magic/char {# ypp-sc-tools pctb font v2}
901     
902 proc read_database_header/char {f} {
903     global rows
904     set l [db_getsl $f]
905     if {$l+0 != $rows} { error "wrong h $l $rows ?" }
906 }
907 proc read_database_entry/char {f context} {
908     global database
909     set bm $context
910     set strq [db_getsl $f]
911     while 1 {
912         set l [db_getsl $f]
913         if {![string length $l]} break
914         lappend bm $l
915     }
916     set database($bm) $strq
917 }
918
919 proc write_database_header/char {f} {
920     global rows
921     puts $f "$rows\n"
922 }
923 proc format_database_entry/char {bm strq} {
924     global database rows
925     set o "[lindex $bm 0]\n$strq\n"
926     foreach x [lrange $bm 1 end] { append o "$x\n" }
927     return $o
928 }
929
930 proc dbkey {ctx l r} {
931     global charkey
932     set bm $ctx
933     for {set x $l} {$x <= $r} {incr x} {
934         lappend bm $charkey($x)
935     }
936     return $bm
937 }
938
939 proc char_get_definition_cursors {} {
940     global cur_0 cur_1
941     if {$cur_0 <= $cur_1} {
942         set cl $cur_0; set cr $cur_1
943     } else {
944         set cl $cur_1; set cr $cur_0
945     }
946     incr cr -1
947     debug "CGD CURSORS $cl $cr"
948     return [list $cl $cr]
949 }
950
951 proc char_get_definition_contexts {} {
952     global glyphsdone unk_l unk_contexts database
953
954     manyset [char_get_definition_cursors] c0 c1
955     
956     if {$c0 == $unk_l} {
957         set ncontexts $unk_contexts
958     } else {
959         foreach {l r context contexts got} $glyphsdone {
960             if {$l==$c0} { set ncontexts $contexts; break }
961         }
962         if {![info exists ncontexts]} {
963             set ncontexts {}
964         }
965     }
966     debug "CGD CONTEXTS $ncontexts"
967     return $ncontexts
968 }
969
970 proc char_get_definition_context_actual {} {
971     global new_context
972     set ncontexts [char_get_definition_contexts]
973     if {[llength $ncontexts]==1} {
974         set c [lindex $ncontexts 0]
975     } elseif {[lsearch -exact $ncontexts $new_context]>=0} {
976         set c $new_context
977     } else {
978         set c {}
979     }
980     debug "CDG CONTEXT ACTUAL $c FROM NEW $new_context ALLOW $ncontexts"
981     return $c
982 }
983
984 proc update_database/DEFINE {strq} {
985     manyset [char_get_definition_cursors] c0 c1
986     set c [char_get_definition_context_actual]
987     if {![string length $c]} {
988         error "Selected context is not one of the many possibilities."
989     }
990     debug "DEFINE $strq"
991     set bm [dbkey $c $c0 $c1]
992     do_database_update $bm $strq
993 }
994
995 proc update_database/DELETE {l r ctxs} {
996     global database
997     if {[llength $ctxs]!=1} { error "$ctxs ?" }
998     foreach ctx $ctxs {
999         set bm [dbkey $ctx $l $r]
1000         catch { unset database($bm) }
1001     }
1002     write_database
1003 }
1004
1005 proc RETURN_RESULT {how what} {
1006     return_result_start
1007
1008     place forget .d.csr.csr
1009     pack forget .d.csr.csr.e
1010
1011     debug "$how $what"
1012     eval update_database/$how $what
1013
1014     return_result_finish
1015 }
1016
1017 #========== server for approving updates ==========
1018
1019 proc remote-serv-log {dict pirate caller file event} {
1020     global remoteserv_logf
1021     set t [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S %Z}]
1022     set s [format "%s %-6s %-31s %-31s %s %s\n" \
1023                $t $dict $pirate $caller [file tail $file] $event]
1024     puts -nonewline $remoteserv_logf $s
1025 }
1026
1027 proc remote-serv/list {} {
1028     global dropdir
1029     foreach file [glob -nocomplain -type f -directory $dropdir _update.*.rdy] {
1030         puts yes
1031         puts $file
1032         set f [open $file]
1033         set d [read $f]
1034         close $f
1035         puts_counted stdout d
1036     }
1037     puts end
1038 }
1039
1040 proc remote-serv/take {yesno file dict} {
1041     global dropdir dictdir rows reqkind database
1042     set rows ""
1043     debug "TAKE [list $yesno $file $dict]"
1044     read_counted stdin pirate
1045     read_counted stdin caller
1046     read_counted stdin key
1047     read_counted stdin val
1048
1049     must_gets_exactly stdin confirmed
1050
1051     manyset [dict2_reqkind_rows $dict] reqkind rows
1052     
1053     if {$yesno} {
1054         read_database $dictdir/master-$dict.txt
1055         set database($key) $val
1056         write_database
1057         set desc approve
1058     } else {
1059         set desc reject
1060     }
1061     remote-serv-log $dict $pirate $caller $file "$desc $reqkind $rows"
1062     file delete -force $file
1063
1064     puts done
1065 }
1066
1067 proc remote-serv/noop {} {
1068     puts ok
1069 }
1070
1071 set remoteserv_banner {ypp-sc-tools pctb remote-server v1}
1072
1073 proc main/remoteserv {} {
1074     global argv dropdir remoteserv_banner remoteserv_logf dictdir
1075     manyset $argv dropdir dictdir
1076     puts $remoteserv_banner
1077     set remoteserv_logf [open $dropdir/_dict.log a]
1078     fconfigure $remoteserv_logf -buffering line
1079     while 1 {
1080         flush stdout
1081         if {[gets stdin l] < 0} break
1082         eval remote-serv/$l
1083     }
1084 }
1085
1086 #========== updates approver ==========
1087
1088 proc puts_server {s} {
1089     global server
1090     debug ">> $s"
1091     puts $server $s
1092 }
1093 proc must_gets_server {lv} {
1094     upvar 1 $lv l
1095     global server
1096     must_gets $server l
1097     debug "<< $l"
1098 }
1099
1100 proc must_gets_exactly_server {expected} {
1101     must_gets_server got
1102     if {[string compare $expected $got]} { error "$expected $got ?" }
1103 }
1104
1105 proc regsub-data {exp subspec args} {
1106     global data
1107     if {![eval regsub $args -- [list $exp $data $subspec data]]} {
1108         error "$exp >$data< ?"
1109     }
1110 }
1111
1112 proc dict2_reqkind_rows {dict} {
1113     if {![string compare pixmap $dict]} {
1114         return {pixmap {}}
1115         debug "DICT PIXMAP"
1116     } elseif {[regexp {^(char)([1-9]\d*)$} $dict dummy reqkind rows]} {
1117         debug "DICT CHAR rqk=$reqkind r=$rows."
1118         return [list $reqkind $rows]
1119     } else {
1120         error "$dict ?"
1121     }
1122 }
1123
1124 proc chop_counted {var} {
1125     upvar 1 $var val
1126     global data
1127     if {![regexp {^(0|[1-9]\d*)\n} $data dummy l]} { error "$data ?" }
1128     regsub-data {^.*\n} {} -line
1129     set val [string range $data 0 [expr {$l-1}]]
1130     set data [string range $data $l end]
1131     debug "CHOP_COUNTED $l $var"
1132     regsub-data {^\n} {}
1133 }
1134
1135 proc approve_decompose_data {specdata} {
1136     global data
1137     set data $specdata
1138     
1139     regsub-data {^ypp-sc-tools dictionary update v2\n} {}
1140     uplevel 1 chop_counted pirate
1141     uplevel 1 chop_counted caller
1142     uplevel 1 chop_counted dict
1143     uplevel 1 chop_counted ctx
1144     uplevel 1 chop_counted def
1145     uplevel 1 chop_counted image
1146     uplevel 1 chop_counted key
1147     uplevel 1 chop_counted val
1148
1149     return [uplevel 1 {list $dict $def $image}]
1150 }
1151
1152 proc approve_compare {fd1 fd2} {
1153     manyset $fd1 file data; set sv1 [approve_decompose_data $data]
1154     manyset $fd2 file data; set sv2 [approve_decompose_data $data]
1155     return [string compare $sv1 $sv2]
1156 }
1157
1158 proc string2unicodenames {str} {
1159     return [exec perl -e {
1160         use Unicode::CharName qw(uname);
1161         $ARGV[0] =~ s/^ //;
1162         foreach $_ (split //,$ARGV[0]) {
1163             print uname(ord),"\n" or die $!
1164         }
1165     } " $str"]
1166 }
1167
1168 proc approve_showentry {ix file specdata} {
1169     global approve_ixes reqkind approve_entryhow
1170     
1171     approve_decompose_data $specdata
1172
1173     set wb .app.e$ix
1174
1175     frame $wb-inf
1176     label $wb-inf.who -text $pirate
1177
1178     entry $wb-inf.file -font fixed -relief flat
1179     $wb-inf.file insert end [file tail $file]
1180     $wb-inf.file configure -state readonly -width -1
1181
1182     pack $wb-inf.who $wb-inf.file -side top
1183
1184     frame $wb-def
1185     label $wb-def.scope -text "$dict $ctx"
1186     label $wb-def.def -text $def
1187     pack $wb-def.scope $wb-def.def -side bottom
1188
1189     if {[regexp {^P2} $image]} {
1190         set image [exec pgmtoppm {#008-white} << $image | pnmnoraw]
1191         append image "\n"
1192     }
1193     set image [exec pnmscale 2 << $image]
1194
1195     image create photo approve/$ix -data $image
1196     label $wb-image -image approve/$ix -bd 2 -relief flat -bg black
1197
1198     manyset [dict2_reqkind_rows $dict] reqkind
1199     approve_showentry_xinfo/$reqkind $wb-xinfo $def
1200
1201     if {$ix} {
1202         label $wb-div -bd 1 -relief sunken -image image/empty
1203         grid configure $wb-div -columnspan 5 -sticky ew -padx 5
1204     }
1205
1206     frame $wb-act -bd 2 -relief groove
1207     set approve_entryhow($ix) approve
1208     foreach how {approve reject defer} {
1209         set w $wb-act.$how
1210         radiobutton $w -variable approve_entryhow($ix) \
1211             -text [string totitle $how] -value $how
1212         pack $w -side left
1213     }
1214
1215     grid $wb-def $wb-image $wb-xinfo $wb-act $wb-inf -padx 3
1216     grid configure $wb-image -ipadx 3 -ipady 3 -sticky w
1217
1218     lappend approve_ixes $ix
1219 }
1220
1221 proc approve_approve_reject_one {ix yesno} {
1222     global approve_list server
1223     manyset [lindex $approve_list $ix] file tdata
1224     approve_decompose_data $tdata
1225     puts_server "take $yesno $file $dict"
1226     puts_counted $server pirate
1227     puts_counted $server caller
1228     puts_counted $server key
1229     puts_counted $server val
1230     puts_server confirmed
1231     flush $server
1232     must_gets_exactly_server done
1233 }
1234
1235 proc approve_check_server {} {
1236     global server
1237     puts_server noop
1238     flush $server
1239     must_gets_exactly_server ok
1240 }
1241
1242 proc approve_confirm {} {
1243     global approve_ixes approve_entryhow
1244     approve_check_server
1245     foreach ix $approve_ixes {
1246         set how $approve_entryhow($ix)
1247         switch -exact $how {
1248             approve { approve_approve_reject_one $ix 1 }
1249             reject  { approve_approve_reject_one $ix 0 }
1250             defer   { }
1251             default { error $how? }
1252         }
1253     }
1254     approve_fetch_list
1255 }
1256
1257 proc approve_fetch_list {} {
1258     global server approve_list
1259     set approve_list {}
1260     puts_server list
1261     flush $server
1262     while 1 {
1263         must_gets_server more
1264         switch -exact $more {
1265             yes { }
1266             end { break }
1267             default { error "$more ?" }
1268         }
1269         must_gets_server file
1270         read_counted $server data
1271         lappend approve_list [list $file $data]
1272     }
1273
1274     if {![llength $approve_list]} { puts "Nothing (more) to approve."; exit 0 }
1275
1276     set approve_list [lsort -command approve_compare $approve_list]
1277     approve_show_page 0
1278 }
1279
1280 proc main/approve {} {
1281     global argv server remoteserv_banner data approve_list approve_page
1282     global userhost directory dictdir debug
1283
1284     if {[llength $argv] != 3} { error "wrong # args" }
1285     manyset $argv userhost directory dictdir
1286     debug "APPROVER FOR $userhost $directory $dictdir"
1287
1288     set cmd [list tclsh $directory/dictionary-manager]
1289     if {$debug} { lappend cmd --debug-server }
1290     lappend cmd --remote-server-1 $directory $dictdir
1291     switch -glob $userhost {
1292         {} { }
1293         {* *} { set cmd $userhost }
1294         * { set cmd [concat [list ssh -o compression=yes $userhost] $cmd] }
1295     }
1296     debug "APPROVER RUNS $cmd"
1297
1298     lappend cmd 2>@ stderr
1299     set server [open |$cmd r+]
1300     must_gets_exactly_server $remoteserv_banner
1301
1302     button .left -text {<<} -command {approve_show_page -1}
1303     button .right -text {>>} -command {approve_show_page +1}
1304
1305     label .title -text {}
1306     frame .app -bd 2 -relief groove
1307     button .ok -text "Confirm" -command approve_confirm
1308     pack .title .app -side top
1309     pack .left -side left
1310     pack .right -side right
1311     pack .ok -side bottom
1312
1313     image create bitmap image/empty
1314
1315     set approve_page 0
1316     approve_fetch_list
1317 }
1318
1319 proc approve_show_page {delta} {
1320     global approve_page approve_ixes approve_list userhost directory dictdir
1321
1322     eval destroy [winfo children .app]
1323     set approve_ixes {}
1324
1325     set per_page 10
1326     incr approve_page $delta
1327
1328     set ll [llength $approve_list]
1329     set npages [expr {($ll+$per_page-1)/$per_page}]
1330     if {$approve_page >= $npages} { incr approve_page -1 }
1331
1332     set page_start [expr {$approve_page*$per_page}]
1333     set page_end [expr {$page_start+$per_page-1}]
1334     
1335     for {set ix $page_start} {$ix < $ll && $ix <= $page_end} {incr ix} {
1336         set fd [lindex $approve_list $ix]
1337         eval approve_showentry $ix $fd
1338     }
1339
1340     .title configure -text \
1341  "$userhost\n$directory => $dictdir\nPage [expr {$approve_page+1}]/$npages"
1342
1343     .left configure -state disabled
1344     .right configure -state disabled
1345     if {$approve_page>0} { .left configure -state normal }
1346     if {$approve_page<$npages-1} { .right configure -state normal }
1347 }
1348
1349 #========== main program ==========
1350
1351 proc return_result_start {} {
1352     helptext {{{ Processing }}}
1353     unbind_all_keys
1354     update idletasks
1355 }
1356 proc return_result_finish {} {
1357     global mainkind
1358     done/$mainkind
1359 }
1360
1361 proc main/default {} {
1362     puts stderr "Do not run this program directly."
1363     exit 12
1364 }
1365 proc done/default {} {
1366 }
1367
1368 proc required {} {
1369     global reqkind
1370
1371     fileevent stdin readable {}
1372     fconfigure stdin -blocking yes
1373     
1374     if {[gets stdin reqkind]<0} {
1375         if {[eof stdin]} { fconfigure stdin -blocking yes; exit 0 }
1376         return
1377     }
1378     init_widgets
1379
1380     required/$reqkind
1381 }
1382
1383 proc main/automatic {} {
1384     fconfigure stdin -blocking no
1385     fileevent stdin readable required
1386 }
1387 proc done/automatic {} {
1388     exec sh -c {printf \\0 >&4}
1389     main/automatic
1390 }
1391
1392 proc debug {m} { }
1393
1394 set mainkind default
1395 set ai 0
1396 set debug 0
1397 set debug_rect 0
1398 set quiet 0
1399 foreach arg $argv {
1400     incr ai
1401     switch -exact -- $arg {
1402         {--quiet}           { set quiet 1 }
1403         {--debug}           { set debug 1 }
1404         {--debug-rect}      { set debug_rect 1 }
1405         {--debug-server}    { proc debug {m} { puts stderr "DICT-MGR-SVR $m" }}
1406         {--noop-arg}        { }
1407         {--approve-updates} { set mainkind approve; break }
1408         {--automatic-1}     { set mainkind automatic; break }
1409         {--remote-server-1} { set mainkind remoteserv; break }
1410         {--automatic*} - {--remote-server}
1411                             { error "incompatible versions - install problem" }
1412         default             { error "huh $argv ?" }
1413     }
1414 }
1415 if {$debug} {
1416     proc debug {m} { puts stderr "DICT-MGR $m" }
1417 }
1418 set argv [lrange $argv $ai end]
1419
1420 main/$mainkind