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