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