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