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