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