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