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