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