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