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