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