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