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