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