chiark / gitweb /
ocean scraper can fetch charts
[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
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
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     }
513 }
514
515 proc upload_status {} {
516     # returns 0, 1, 2 for none, anon, with pirate name
517     global env
518
519     if {![info exists env(YPPSC_YARRG_DICT_SUBMIT)]} { debug a; return 0 }
520     if {![string compare 0 $env(YPPSC_YARRG_DICT_SUBMIT)]} { debug b; return 0 }
521
522     if {![info exists env(YPPSC_PIRATE)]} { return 1 }
523     if {![info exists env(YPPSC_OCEAN)]} { return 1 }
524     if {![string length $env(YPPSC_PIRATE)]} { return 1 }
525     if {![string length $env(YPPSC_OCEAN)]} { return 1 }
526
527     return 2
528 }
529
530 proc maybe_upload_entry {im def} {
531     global reqkind privacy_setting env dbname quiet aadepth
532
533     debug "DB-UPDATE PRIVACY $privacy_setting"
534     if {!$privacy_setting} return
535
536     debug "DB-UPDATE UPLOADING"
537
538     set pl {}
539     lappend pl dict $dbname
540     lappend pl version 3
541     lappend pl depth $aadepth
542
543     if {$privacy_setting>=2} {
544         set pirate [string totitle $env(YPPSC_PIRATE)]
545         set ocean [string totitle $env(YPPSC_OCEAN)]
546         debug "DB-UPDATE NON-ANON $ocean $pirate"
547         lappend pl \
548             pirate $pirate \
549             ocean $ocean
550     }
551     lappend pl entry [format_database_entry/$reqkind $im $def]
552
553     set url $env(YPPSC_YARRG_DICT_SUBMIT)
554     append url dictionary-update-receiver
555
556     set query [eval ::http::formatQuery $pl]
557     regsub -all {%0d} $query {} query
558     debug "DB-UPDATE QUERY $query"
559
560     if {[regexp {^\.?/} $url]} {
561         set cmd [list $url $query]
562         debug "SUBMIT CMD [string range $cmd 0 200]..."
563         set body [eval exec $cmd 2>@ stderr]
564         regsub {^Content-Type: text/plain.*\n\n} $body {} body
565     } else {
566
567         if {[catch {
568             set req [::http::geturl $url -query $query]
569         } emsg]} {
570             puts stderr \
571                 "\nWARNING: Cannot do dictionary upload: $emsg\n"
572             return
573         }
574         upvar #0 $req s
575         debug "DB-UPDATE DONE $req $s(status) [array names s]"
576         set ncode [::http::ncode $req]
577
578         if {!(![string compare ok $s(status)] &&
579               ![string compare 200 $ncode])} {
580             set m "\nWARNING: Dictionary upload failed:"
581             foreach v {status http error posterror} {
582                 if {[info exists s($v)]} { append m "\n $v: $s($v)" }
583             }
584             puts stderr $m
585             return
586         }
587         set body $s(body)
588         ::http::cleanup $req
589     }
590
591     if {![string match {OK *} $body]} {
592         set m "\nWARNING: Dictionary upload went wrong:\n"
593         append m "\n  " [join [split $body "\n"] "\n  "]
594         puts stderr $m
595         return
596     }
597
598     if {!$quiet} {
599         puts stderr \
600             "Uploaded $dbname `$def': $body"
601     }
602 }
603
604 #========== CHARACTER SET ==========
605
606 #---------- pgm input processor ----------
607
608 proc char_read_pgm {f} {
609     global glyphsdone mul inter rhsmost_max unk_l unk_r mulcols mulrows
610     global cols rows charkey
611     
612     must_gets_imagel $f l
613     if {[string compare $l P2]} { error "magic $l ?" }
614
615     must_gets_imagel $f l
616     if {![regexp {^([1-9]\d{0,3}) ([1-9]\d{0,3}) ([1-9]\d?)$} \
617               $l dummy cols rows maxval]} { error "head $l ?" }
618
619     for {set depth 1} {$maxval != (1<<$depth)-1} {incr depth} {
620         if {$depth >= 16} { error "maxval $maxval ?" }
621     }
622
623     set chop_l [expr {$unk_l - 80}]
624     set chop_r [expr {$cols - $unk_l - 100}]
625     if {$chop_l<0} { set chop_l 0 }
626     if {$chop_r<0} { set chop_r 0 }
627
628     set unk_l [expr {$unk_l - $chop_l}]
629     set unk_r [expr {$unk_r - $chop_l}]
630     set ngd {}
631     foreach {min max context contexts got} $glyphsdone {
632         lappend ngd \
633             [expr {$min-$chop_l}] \
634             [expr {$max-$chop_l}] \
635             $context $contexts $got
636     }
637     set glyphsdone $ngd
638
639     set realcols $cols
640     set cols [expr {$cols - $chop_l - $chop_r}]
641     debug "NOW cols=$cols chop_l,r=$chop_l,$chop_r rows=$rows\
642                 $unk_l $unk_r $ngd"
643
644     set mulcols [expr {$cols*$mul+$inter}]
645     set mulrows [expr {$rows*$mul+$inter}]
646
647     set o "P3\n$mulcols $mulrows 15\n"
648
649     for {set x 0} {$x<$cols} {incr x} { set charkey($x) {} }
650
651     set ointer1 "   1  1  1"
652     set ointer  [string repeat $ointer1 $inter]
653     set ointerl "[string repeat $ointer1 $mulcols]\n"
654
655     append o $ointerl
656     
657     for {set y 0} {$y<$rows} {incr y} {
658         must_gets_imagel $f l
659         if {[llength $l] != $realcols} { error "realcols=$realcols $l ?" }
660
661         set ol $ointer
662
663         for {set x 0} {$x<$cols} {incr x} {
664             set realx [expr {$x + $chop_l}]
665             set c [lindex $l $realx]
666             append charkey($x) [format %x $c]
667
668             set how "u"
669             if {$x >= $unk_l && $x <= $unk_r} {
670                 set how q
671             } else {
672                 set ab 0
673                 foreach {min max context contexts got} $glyphsdone {
674                     set rhsmost_max $max
675                     if {$x >= $min && $x <= $max} {
676                         set how [lindex {a b} $ab]
677                         break
678                     }
679                     set ab [expr {!$ab}]
680                 }
681             }
682             set c15 [expr {$c << (16-$depth)}]
683             set c15 [expr {$c15 | ($c15 >> $depth)}]
684             set c15 [expr {$c15 | ($c15 >> $depth*2)}]
685             set c15 [expr {$c15 >> 12}]
686
687             foreach rgb {r g b} { set $rgb {$c15} }
688             switch -exact $how {
689                 a { set r {$c15>>1 | 0x8} }
690                 b { set b {$c15>>2 | 0xc} }
691                 u { set b  0              }
692                 q { set b  0              }
693                 default { error "how $how ?" }
694             }
695 #debug "PIXEL $x,$y how=$how c=$c c15=$c15 $r $g $b"
696
697             set opixel " "
698             foreach rgb {r g b} {
699                 append opixel [format " %2d" [expr [set $rgb]]]
700             }
701             append ol [string repeat $opixel [expr {$mul-$inter}]]
702             append ol $ointer
703         }
704         append ol "\n"
705         append o [string repeat $ol [expr {$mul-$inter}]]
706         append o $ointerl
707     }
708
709 #    debug "DATA1 $o"
710
711     execpnm_createphoto image/main  pnmscale 1 << $o
712 }
713
714 #---------- character set editor display ----------
715
716 proc show_context {maxhv x ctxs} {
717     global mul
718     upvar 1 $maxhv maxh
719     set w .d.ctx.at$x
720     if {[llength $ctxs]==1} { set fg blue } { set fg yellow }
721     label $w -bg black -fg $fg -text [join $ctxs "/\n"] -justify left
722     place $w -x [expr {($x-1)*$mul}] -y 0
723     set wh [winfo reqheight $w]
724     if {$wh > $maxh} { set maxh $wh }
725 }
726
727 proc draw_glyphsdone {} {
728     global glyphsdone mul inter
729     eval destroy [winfo children .d.got]
730     foreach {min max context contexts got} $glyphsdone {
731         frame .d.got.m$min -bd 0 -background \#888
732         label .d.got.m$min.l -text "$got" -fg white -bg black -bd 0
733         pack .d.got.m$min.l -padx 1 -pady 1
734         place .d.got.m$min -x [expr {$min*$mul+$inter}] -y 0
735     }
736 }
737
738 proc startup_cursor {} {
739     global cur_already cur_mode cur_0 cur_1 last_ht
740     global glyphsdone unk_l unk_r
741     
742     set cur_already [expr {[llength $glyphsdone]/5-1}]
743     set cur_mode 0 ;# one of:   0 1 already text
744
745     set cur_0 $unk_l
746     set cur_1 [expr {$unk_r+1}]
747
748     recursor
749 }
750
751 #---------- character set runtime display and keystroke handling ----------
752
753 proc char_exactly_selctxts {contexts} {
754     global all_contexts
755     foreach ctx [array names all_contexts] {
756         set ci $all_contexts($ctx)
757         set selw .selctx.c$ci
758         if {[lsearch -exact $contexts $ctx]>=0} {
759             set state normal
760         } else {
761             set state disabled
762         }
763         $selw configure -state $state
764     }
765 }
766
767 proc recursor/0 {} { recursor//01 0 }
768 proc recursor/1 {} { recursor//01 1 }
769 proc recursor//01 {z1} {
770     global mul rhsmost_max cols glyphsdone cur_0 cur_1
771     global all_contexts
772     upvar #0 cur_$z1 cur
773     .d.csr.csr.l configure -text "adjust [char_get_definition_context_actual]"
774     place .d.csr.csr -x [expr {$cur*$mul - 7}]
775
776     set okctxts [char_get_definition_contexts]
777     char_exactly_selctxts $okctxts
778
779     foreach ctx [lsort [array names all_contexts]] {
780         set key [string range $ctx 0 0]
781         if {[lsearch -exact $okctxts $ctx] >= 0} {
782             bind_key [string tolower $key] "
783                 [list set new_context $ctx]
784                 char_start_define_text
785             "
786         } else {
787             bind_key [string tolower $key] {}
788         }
789         lappend context_help $key
790     }
791     set context_help [list [join $context_help " "] \
792       {Set match context for new glyph, confirm location, and start entry.}]
793
794     bind_key space { othercursor }
795     bind_leftright_q cur_$z1 0 [expr {$cols-1}]
796     if {[llength $glyphsdone]} {
797         bind_key BackSpace { set cur_mode already; recursor }
798     } else {
799         bind_key BackSpace {}
800     }
801     bind_key Return {
802         char_start_define_text
803     }
804     helptext [list                                              \
805         {{<- ->}   {move cursor, adjusting area to define}}     \
806         {Space     {switch to moving other cursor}}             \
807         {Return    {confirm location, enter letter(s)}}         \
808         {Backspace {switch to correcting earlier ocr}}          \
809         {Q         {quit and abandon OCR run}}                  \
810         $context_help                                           \
811                   ]
812 }
813 proc othercursor {} {
814     global cur_mode
815     set cur_mode [expr {!$cur_mode}]
816     recursor
817 }
818
819 proc char_start_define_text {} {
820     global cur_0 cur_1 cur_mode
821     if {$cur_0 == $cur_1} return
822     set cdgdca [char_get_definition_context_actual]
823     if {![string length $cdgdca]} return
824     .d.csr.csr.e delete 0 end
825     set cur_mode text
826     .d.csr.csr.l configure -text "define $cdgdca:"
827     recursor
828 }
829
830 proc recursor/text {} {
831     global all_contexts
832     
833     helptext {
834         {Return   {confirm entry of new glyph}}
835         {Escape   {abandon entry}}
836     }
837     unbind_all_keys
838     pack .d.csr.csr.e -side left -padx 2
839     focus .d.csr.csr.e
840     bind .d.csr.csr.e <Key-Return> {
841         set strq [.d.csr.csr.e get]
842         if {[string length $strq]} {
843             RETURN_RESULT DEFINE [list $strq]
844         }
845     }
846     bind .d.csr.csr.e <Key-Escape> {
847         bind_key Escape {}
848         pack forget .d.csr.csr.e
849         set cur_mode 1
850         focus .d
851         recursor
852     }
853 }
854
855 proc recursor/already {} {
856     global mul
857     global cur_already mul
858     global glyphsdone cur_already mul
859
860     char_exactly_selctxts [lindex $glyphsdone [expr {$cur_already*5+2}]]
861
862     .d.csr.csr.l configure -text {correct}
863     set rmax [lindex $glyphsdone [expr {$cur_already*5}]]
864     place .d.csr.csr -x [expr {$rmax*$mul-3}]
865     bind_key Return {}
866     bind_leftright_q cur_already 0 [expr {[llength $glyphsdone]/5-1}]
867     bind_key space { bind_key Delete {}; set cur_mode 1; recursor }
868     bind_key Delete {
869         RETURN_RESULT DELETE [lrange $glyphsdone \
870                                   [expr $cur_already*5] \
871                                   [expr $cur_already*5+2]]
872     }
873     helptext {
874         {{<- ->}   {move cursor, selecting glyph to correct}}
875         {Del       {clear this glyph from the recognition database}}
876         {Space     {switch to selecting area to define as new glyph}}
877         {Q         {quit and abandon OCR run}}
878     }
879 }
880
881 proc bind_leftright_q {var min max} {
882     bind_key Left  [list leftright $var $min $max -1]
883     bind_key Right [list leftright $var $min $max +1]
884     bind_key q     {
885         puts stderr "\nCharacter resolver quitting as you requested."
886         exit 1
887     }
888 }
889 proc leftright {var min max inc} {
890     upvar #0 $var v
891     set vnew $v
892     incr vnew $inc
893     if {$vnew < $min || $vnew > $max} return
894     set v $vnew
895     recursor
896 }
897
898 proc recursor {} {
899     global csrh cur_mode cur_0 cur_1 mul
900     foreach z1 {0 1} {
901         place .d.mi.csr_$z1 -y 0 -x [expr {[set cur_$z1] * $mul}]
902     }
903     recursor/$cur_mode
904 }
905
906 #---------- character database read and write ----------
907
908 # OUT OF DATE
909 # database format:
910 # series of glyphs:
911 #   <context> <ncharacters> <hex>...
912 #   width
913 #   <hex-bitmap>
914
915 # $database($context 0x<bits> 0x<bits>...) = $hex
916
917 set database_magic/char "# ypp-sc-tools pctb font v3 depth=$aadepth"
918     
919 proc read_database_header/char {f} {
920     global rows
921     set l [db_getsl $f]
922     if {$l+0 != $rows} { error "wrong h $l $rows ?" }
923 }
924 proc read_database_entry/char {f context} {
925     global database
926     set bm $context
927     set strq [db_getsl $f]
928     while 1 {
929         set l [db_getsl $f]
930         if {![string length $l]} break
931         lappend bm $l
932     }
933     set database($bm) $strq
934 }
935
936 proc write_database_header/char {f} {
937     global rows
938     puts $f "$rows\n"
939 }
940 proc format_database_entry/char {bm strq} {
941     global database rows
942     set o "[lindex $bm 0]\n$strq\n"
943     foreach x [lrange $bm 1 end] { append o "$x\n" }
944     return $o
945 }
946
947 proc dbkey {ctx l r} {
948     global charkey
949     set bm $ctx
950     for {set x $l} {$x <= $r} {incr x} {
951         lappend bm $charkey($x)
952     }
953     return $bm
954 }
955
956 proc char_get_definition_cursors {} {
957     global cur_0 cur_1
958     if {$cur_0 <= $cur_1} {
959         set cl $cur_0; set cr $cur_1
960     } else {
961         set cl $cur_1; set cr $cur_0
962     }
963     incr cr -1
964     debug "CGD CURSORS $cl $cr"
965     return [list $cl $cr]
966 }
967
968 proc char_get_definition_contexts {} {
969     global glyphsdone unk_l unk_contexts database
970
971     manyset [char_get_definition_cursors] c0 c1
972     
973     if {$c0 == $unk_l} {
974         set ncontexts $unk_contexts
975     } else {
976         foreach {l r context contexts got} $glyphsdone {
977             if {$l==$c0} { set ncontexts $contexts; break }
978         }
979         if {![info exists ncontexts]} {
980             set ncontexts {}
981         }
982     }
983     debug "CGD CONTEXTS $ncontexts"
984     return $ncontexts
985 }
986
987 proc char_get_definition_context_actual {} {
988     global new_context
989     set ncontexts [char_get_definition_contexts]
990     if {[llength $ncontexts]==1} {
991         set c [lindex $ncontexts 0]
992     } elseif {[lsearch -exact $ncontexts $new_context]>=0} {
993         set c $new_context
994     } else {
995         set c {}
996     }
997     debug "CDG CONTEXT ACTUAL $c FROM NEW $new_context ALLOW $ncontexts"
998     return $c
999 }
1000
1001 proc update_database/DEFINE {strq} {
1002     manyset [char_get_definition_cursors] c0 c1
1003     set c [char_get_definition_context_actual]
1004     if {![string length $c]} {
1005         error "Selected context is not one of the many possibilities."
1006     }
1007     debug "DEFINE $strq"
1008     set bm [dbkey $c $c0 $c1]
1009     do_database_update $bm $strq
1010 }
1011
1012 proc update_database/DELETE {l r ctxs} {
1013     global database
1014     if {[llength $ctxs]!=1} { error "$ctxs ?" }
1015     foreach ctx $ctxs {
1016         set bm [dbkey $ctx $l $r]
1017         catch { unset database($bm) }
1018     }
1019     write_database
1020 }
1021
1022 proc RETURN_RESULT {how what} {
1023     return_result_start
1024
1025     place forget .d.csr.csr
1026     pack forget .d.csr.csr.e
1027
1028     debug "$how $what"
1029     eval update_database/$how $what
1030
1031     return_result_finish
1032 }
1033
1034 #========== server for approving updates ==========
1035
1036 proc remote-serv-log {dict pirate caller file event} {
1037     global remoteserv_logf
1038     set t [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S %Z}]
1039     set s [format "%s %-6s %-31s %-31s %s %s\n" \
1040                $t $dict $pirate $caller [file tail $file] $event]
1041     puts -nonewline $remoteserv_logf $s
1042 }
1043
1044 proc remote-serv/list {} {
1045     global dropdir
1046     foreach file [glob -nocomplain -type f -directory $dropdir _update.*.rdy] {
1047         puts yes
1048         puts $file
1049         set f [open $file]
1050         set d [read $f]
1051         close $f
1052         puts_counted stdout d
1053     }
1054     puts end
1055 }
1056
1057 proc remote-serv/take {yesno file dict} {
1058     global dropdir dictdir rows reqkind database
1059     set rows ""
1060     debug "TAKE [list $yesno $file $dict]"
1061     read_counted stdin pirate
1062     read_counted stdin caller
1063     read_counted stdin key
1064     read_counted stdin val
1065
1066     must_gets_exactly stdin confirmed
1067
1068     manyset [dict2_reqkind_rows $dict] reqkind rows
1069     
1070     if {$yesno} {
1071         set fnbase $dictdir/master-$dict.txt
1072         read_database $fnbase
1073         set database($key) $val
1074         write_database
1075
1076         exec gzip --rsyncable -7 < $fnbase > $fnbase.gz.new
1077         exec mv -f -- $fnbase.gz.new $fnbase.gz
1078
1079         set desc approve
1080     } else {
1081         set desc reject
1082     }
1083     remote-serv-log $dict $pirate $caller $file "$desc $reqkind $rows"
1084     file delete -force $file
1085
1086     puts done
1087 }
1088
1089 proc remote-serv/noop {} {
1090     puts ok
1091 }
1092
1093 set remoteserv_banner {ypp-sc-tools pctb remote-server v1}
1094
1095 proc main/remoteserv {} {
1096     global argv dropdir remoteserv_banner remoteserv_logf dictdir
1097     manyset $argv dropdir dictdir
1098     puts $remoteserv_banner
1099     set remoteserv_logf [open $dropdir/_dict.log a]
1100     fconfigure $remoteserv_logf -buffering line
1101     while 1 {
1102         flush stdout
1103         if {[gets stdin l] < 0} break
1104         eval remote-serv/$l
1105     }
1106 }
1107
1108 #========== updates approver ==========
1109
1110 proc puts_server {s} {
1111     global server
1112     debug ">> $s"
1113     puts $server $s
1114 }
1115 proc must_gets_server {lv} {
1116     upvar 1 $lv l
1117     global server
1118     must_gets $server l
1119     debug "<< $l"
1120 }
1121
1122 proc must_gets_exactly_server {expected} {
1123     must_gets_server got
1124     if {[string compare $expected $got]} { error "$expected $got ?" }
1125 }
1126
1127 proc regsub-data {exp subspec args} {
1128     global data
1129     if {![eval regsub $args -- [list $exp $data $subspec data]]} {
1130         error "$exp >$data< ?"
1131     }
1132 }
1133
1134 proc dict2_reqkind_rows {dict} {
1135     if {![string compare pixmap $dict]} {
1136         return {pixmap {}}
1137         debug "DICT PIXMAP"
1138     } elseif {[regexp {^(char)([1-9]\d*)$} $dict dummy reqkind rows]} {
1139         debug "DICT CHAR rqk=$reqkind r=$rows."
1140         return [list $reqkind $rows]
1141     } else {
1142         error "$dict ?"
1143     }
1144 }
1145
1146 proc chop_counted {var} {
1147     upvar 1 $var val
1148     global data
1149     if {![regexp {^(0|[1-9]\d*)\n} $data dummy l]} { error "$data ?" }
1150     regsub-data {^.*\n} {} -line
1151     set val [string range $data 0 [expr {$l-1}]]
1152     set data [string range $data $l end]
1153     debug "CHOP_COUNTED $l $var"
1154     regsub-data {^\n} {}
1155 }
1156
1157 proc approve_decompose_data {specdata} {
1158     global data aadepth
1159     set data $specdata
1160     
1161     regsub-data "^ypp-sc-tools dictionary update v3 depth=$aadepth\\n" {}
1162     uplevel 1 chop_counted pirate
1163     uplevel 1 chop_counted caller
1164     uplevel 1 chop_counted dict
1165     uplevel 1 chop_counted ctx
1166     uplevel 1 chop_counted def
1167     uplevel 1 chop_counted image
1168     uplevel 1 chop_counted key
1169     uplevel 1 chop_counted val
1170
1171     return [uplevel 1 {list $dict $ctx $def $image}]
1172 }
1173
1174 proc approve_compare {fd1 fd2} {
1175     manyset $fd1 file data; set sv1 [approve_decompose_data $data]
1176     manyset $fd2 file data; set sv2 [approve_decompose_data $data]
1177     return [string compare $sv1 $sv2]
1178 }
1179
1180 proc string2unicodenames {str} {
1181     return [exec perl -e {
1182         use Unicode::CharName qw(uname);
1183         $ARGV[0] =~ s/^ //;
1184         foreach $_ (split //,$ARGV[0]) {
1185             print uname(ord),"\n" or die $!
1186         }
1187     } " $str"]
1188 }
1189
1190 proc approve_showentry {ix file specdata} {
1191     global approve_ixes reqkind approve_entryhow
1192     
1193     approve_decompose_data $specdata
1194
1195     set wb .app.e$ix
1196
1197     frame $wb-inf
1198     label $wb-inf.who -text $pirate
1199
1200     entry $wb-inf.file -font fixed -relief flat
1201     $wb-inf.file insert end [file tail $file]
1202     $wb-inf.file configure -state readonly -width -1
1203
1204     pack $wb-inf.who $wb-inf.file -side top
1205
1206     frame $wb-def
1207     label $wb-def.scope -text "$dict $ctx"
1208     label $wb-def.def -text $def
1209     pack $wb-def.scope $wb-def.def -side bottom
1210
1211     if {[regexp {^P2} $image]} {
1212         set image [exec pgmtoppm {#008-white} << $image | pnmnoraw]
1213         append image "\n"
1214     }
1215     execpnm_createphoto approve/$ix  pnmscale 3 << $image
1216     label $wb-image -image approve/$ix -bd 2 -relief flat -bg black
1217
1218     manyset [dict2_reqkind_rows $dict] reqkind
1219     approve_showentry_xinfo/$reqkind $wb-xinfo $def
1220
1221     if {$ix} {
1222         label $wb-div -bd 1 -relief sunken -image image/empty
1223         grid configure $wb-div -columnspan 5 -sticky ew -padx 5
1224     }
1225
1226     frame $wb-act -bd 2 -relief groove
1227     set approve_entryhow($ix) approve
1228     foreach how {approve reject defer} {
1229         set w $wb-act.$how
1230         radiobutton $w -variable approve_entryhow($ix) \
1231             -text [string totitle $how] -value $how
1232         pack $w -side left
1233     }
1234
1235     grid $wb-def $wb-image $wb-xinfo $wb-act $wb-inf -padx 3
1236     grid configure $wb-image -ipadx 3 -ipady 3 -sticky w
1237
1238     lappend approve_ixes $ix
1239 }
1240
1241 proc approve_approve_reject_one {ix yesno} {
1242     global approve_list server
1243     manyset [lindex $approve_list $ix] file tdata
1244     approve_decompose_data $tdata
1245     puts_server "take $yesno $file $dict"
1246     puts_counted $server pirate
1247     puts_counted $server caller
1248     puts_counted $server key
1249     puts_counted $server val
1250     puts_server confirmed
1251     flush $server
1252     must_gets_exactly_server done
1253 }
1254
1255 proc approve_check_server {} {
1256     global server
1257     puts_server noop
1258     flush $server
1259     must_gets_exactly_server ok
1260 }
1261
1262 proc approve_confirm {} {
1263     global approve_ixes approve_entryhow
1264     .ok configure -state disabled
1265     update idletasks
1266     approve_check_server
1267     foreach ix $approve_ixes {
1268         set how $approve_entryhow($ix)
1269         switch -exact $how {
1270             approve { approve_approve_reject_one $ix 1 }
1271             reject  { approve_approve_reject_one $ix 0 }
1272             defer   { }
1273             default { error $how? }
1274         }
1275     }
1276     approve_fetch_list
1277 }
1278
1279 proc approve_fetch_list {} {
1280     global server approve_list
1281     set approve_list {}
1282     puts_server list
1283     flush $server
1284     while 1 {
1285         must_gets_server more
1286         switch -exact $more {
1287             yes { }
1288             end { break }
1289             default { error "$more ?" }
1290         }
1291         must_gets_server file
1292         read_counted $server data
1293         lappend approve_list [list $file $data]
1294     }
1295
1296     if {![llength $approve_list]} { puts "Nothing (more) to approve."; exit 0 }
1297
1298     set approve_list [lsort -command approve_compare $approve_list]
1299     approve_show_page 0
1300     .ok configure -state normal
1301 }
1302
1303 proc main/approve {} {
1304     global argv server remoteserv_banner data approve_list approve_page
1305     global userhost directory dictdir debug
1306
1307     if {[llength $argv] != 3} { error "wrong # args" }
1308     manyset $argv userhost directory dictdir
1309     debug "APPROVER FOR $userhost $directory $dictdir"
1310
1311     set cmd [list tclsh $directory/dictionary-manager]
1312     if {$debug} { lappend cmd --debug-server }
1313     lappend cmd --remote-server-1 $directory $dictdir
1314     switch -glob $userhost {
1315         {} { }
1316         {* *} { set cmd $userhost }
1317         * { set cmd [concat [list ssh -o compression=yes $userhost] $cmd] }
1318     }
1319     debug "APPROVER RUNS $cmd"
1320
1321     lappend cmd 2>@ stderr
1322     set server [open |$cmd r+]
1323     must_gets_exactly_server $remoteserv_banner
1324
1325     button .left -text {<<} -command {approve_show_page -1}
1326     button .right -text {>>} -command {approve_show_page +1}
1327
1328     label .title -text {}
1329     frame .app -bd 2 -relief groove
1330     button .ok -text "Confirm" -command approve_confirm
1331     pack .title .app -side top
1332     pack .left -side left
1333     pack .right -side right
1334     pack .ok -side bottom
1335
1336     image create bitmap image/empty
1337
1338     set approve_page 0
1339     approve_fetch_list
1340 }
1341
1342 proc approve_show_page {delta} {
1343     global approve_page approve_ixes approve_list userhost directory dictdir
1344
1345     eval destroy [winfo children .app]
1346     set approve_ixes {}
1347
1348     set per_page 10
1349     incr approve_page $delta
1350
1351     set ll [llength $approve_list]
1352     set npages [expr {($ll+$per_page-1)/$per_page}]
1353     if {$approve_page >= $npages} { incr approve_page -1 }
1354
1355     set page_start [expr {$approve_page*$per_page}]
1356     set page_end [expr {$page_start+$per_page-1}]
1357     
1358     for {set ix $page_start} {$ix < $ll && $ix <= $page_end} {incr ix} {
1359         set fd [lindex $approve_list $ix]
1360         eval approve_showentry $ix $fd
1361     }
1362
1363     .title configure -text \
1364  "$userhost\n$directory => $dictdir\nPage [expr {$approve_page+1}]/$npages"
1365
1366     .left configure -state disabled
1367     .right configure -state disabled
1368     if {$approve_page>0} { .left configure -state normal }
1369     if {$approve_page<$npages-1} { .right configure -state normal }
1370 }
1371
1372 #========== main program ==========
1373
1374 proc return_result_start {} {
1375     helptext {{{ Processing }}}
1376     unbind_all_keys
1377     update idletasks
1378 }
1379 proc return_result_finish {} {
1380     global mainkind
1381     done/$mainkind
1382 }
1383
1384 proc main/default {} {
1385     puts stderr "Do not run this program directly."
1386     exit 12
1387 }
1388 proc done/default {} {
1389 }
1390
1391 proc required {} {
1392     global reqkind
1393
1394     fileevent stdin readable {}
1395     fconfigure stdin -blocking yes
1396     
1397     if {[gets stdin reqkind]<0} {
1398         if {[eof stdin]} { fconfigure stdin -blocking yes; exit 0 }
1399         return
1400     }
1401     init_widgets
1402
1403     required/$reqkind
1404 }
1405
1406 proc main/automatic {} {
1407     fconfigure stdin -blocking no
1408     fileevent stdin readable required
1409 }
1410 proc done/automatic {} {
1411     exec sh -c {printf \\0 >&4}
1412     main/automatic
1413 }
1414
1415 proc debug {m} { }
1416
1417 set mainkind default
1418 set ai 0
1419 set debug 0
1420 set debug_rect 0
1421 set quiet 0
1422 foreach arg $argv {
1423     incr ai
1424     switch -exact -- $arg {
1425         {--quiet}           { set quiet 1 }
1426         {--debug}           { set debug 1 }
1427         {--debug-rect}      { set debug_rect 1 }
1428         {--debug-server}    { proc debug {m} { puts stderr "DICT-MGR-SVR $m" }}
1429         {--noop-arg}        { }
1430         {--approve-updates} { set mainkind approve; break }
1431         {--automatic-1}     { set mainkind automatic; break }
1432         {--remote-server-1} { set mainkind remoteserv; break }
1433         {--automatic*} - {--remote-server}
1434                             { error "incompatible versions - install problem" }
1435         default             { error "huh $argv ?" }
1436     }
1437 }
1438 if {$debug} {
1439     proc debug {m} { puts stderr "DICT-MGR $m" }
1440 }
1441 set argv [lrange $argv $ai end]
1442
1443 main/$mainkind