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