chiark / gitweb /
c2ea2b59f5b371fe99d72de6afa30b27123c468b
[ypp-sc-tools.web-live.git] / pctb / dictionary-manager
1 #!/usr/bin/wish
2
3 # helper program for OCR in PCTB upload client
4
5 # This is part of ypp-sc-tools, a set of third-party tools for assisting
6 # players of Yohoho Puzzle Pirates.
7 #
8 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
9 #
10 # This program is free software: you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation, either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 #
23 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
24 # are used without permission.  This program is not endorsed or
25 # sponsored by Three Rings.
26
27
28 # invocation:
29 # OUT OF DATE
30 #  run this without args
31 #  then on stdin write
32 #     one line which is a Tcl list for unk_{l,r} unk_contexts glyphsdone etc.
33 #     the xpm in the format expected
34 #  then expect child to exit 0, or write a single 0 byte to fd 4
35 #  if it wrote a byte to fd 4, it can take another question
36
37
38 #---------- library routines ----------
39
40 proc manyset {list args} {
41     foreach val $list var $args {
42         upvar 1 $var my
43         set my $val
44     }
45 }
46
47 proc must_gets {f lvar} {
48     upvar 1 $lvar l
49     if {[gets $f l] < 0} { error "huh?" }
50 }
51
52 proc must_gets_exactly {f expected} {
53     must_gets $f got
54     if {[string compare $expected $got]} { error "$expected $got ?" }
55 }
56
57 proc read_counted {f var} {
58     upvar 1 $var val
59     must_gets $f count
60     set val [read $f $count]
61     must_gets $f eol
62     if {[string length $eol]} { error "$eol ?" }
63     debug "READ_COUNTED $count $var"
64 }
65
66 proc puts_counted {f dvar} {
67     upvar 1 $dvar d
68     set count [string length $d]
69     puts $f $count
70     puts $f $d
71     debug "PUTS_COUNTED $count $dvar"
72 }
73
74 #---------- display core ----------
75
76 set mul 6
77 set inter 1
78
79 set gotsh 20
80 set csrh 20
81 set ctxh 20
82
83 proc init_widgets {} {
84     # idempotent
85     global csrh gotsh ctxh
86
87     if {[winfo exists .d]} return
88
89     frame .privacy -bd 2 -relief groove
90     pack .privacy -side top -padx 2 -pady 2 -fill x
91
92     upload_init_widgets
93     
94     frame .d -bd 2 -relief groove -pady 2 -padx 2
95
96     image create bitmap image/main
97     label .d.mi -image image/main -borderwidth 0
98
99     frame .d.csr -bg black -height $csrh
100     frame .d.got -bg black -height $gotsh
101     frame .d.ctx -bg black
102
103     image create bitmap image/cursor -data \
104 {#define csr_width 11
105 #define csr_height 11
106 static unsigned char csr_bits[] = {
107    0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x21, 0x04, 0x22, 0x02, 0x25, 0x05,
108    0xaa, 0x02, 0x74, 0x01, 0xa8, 0x00, 0x70, 0x00, 0x20, 0x00};
109 }
110
111     frame .d.csr.csr
112     label .d.csr.csr.l -image image/cursor -compound left
113     entry .d.csr.csr.e -bd 0
114     pack .d.csr.csr.l -side left
115
116     frame .d.mi.csr_0 -bg white -width 1
117     frame .d.mi.csr_1 -bg white -width 1
118     frame .d.pe
119     frame .d.pe.grid
120
121     button .d.pe.ok -text OK
122     pack .d.pe.grid .d.pe.ok -side left
123
124     pack .d.mi .d.ctx -side top
125     pack .d -fill x -padx 2 -pady 2
126
127     frame .help -bd 2 -relief groove
128     pack .help -pady 2 -padx 2
129 }
130
131 proc resize_widgets_core {} {
132     global mulcols mulrows csrh gotsh ctxh glyphsdone
133     global unk_l unk_contexts
134     
135     foreach w {.d.csr .d.got .d.ctx} {
136         $w configure -width $mulcols
137     }
138
139     eval destroy [winfo children .d.ctx]
140 }
141
142 set last_ht {}
143
144 proc helptext {t} {
145     global last_ht
146     if {![string compare $t $last_ht]} return
147     eval destroy [grid slaves .help]
148     set y 0; foreach l $t {
149         set x 0; foreach c $l {
150             set w .help.at${x}x${y}
151             label $w -text $c
152             grid $w -row $y -column $x -padx 5 -sticky w
153             incr x
154         }
155         incr y
156     }
157     set last_ht $t
158 }
159
160 proc bind_key {k proc} {
161     global keybindings
162     bind . <Key-$k> $proc
163     set keybindings($k) [expr {!![string length $proc]}]
164 }
165 proc unbind_all_keys {} {
166     global keybindings
167     foreach k [array names keybindings] { bind_key $k {} }
168 }
169
170 #---------- database read and write common wrapper ----------
171
172 proc db_getsl {f} {
173     if {[gets $f l] < 0} { error "unexpected db eof" }
174     return $l
175 }
176
177 proc read_database {fn} {
178     global reqkind database database_fn
179     upvar #0 database_magic/$reqkind magic
180     catch { unset database }
181
182     set database_fn $fn
183     if {![file exists $database_fn]} return
184     set f [open $database_fn r]
185     if {[string compare [db_getsl $f] $magic]} { error "$l $reqkind ?" }
186
187     read_database_header/$reqkind $f
188     while 1 {
189         set l1 [db_getsl $f]
190     
191         if {![string length $l1]} continue
192         if {[regexp {^\#} $l1]} continue
193         if {![string compare . $l1]} break
194
195         read_database_entry/$reqkind $f $l1
196     }
197     close $f
198 }
199
200 proc write_database {} {
201     global reqkind database_fn database
202     upvar #0 database_magic/$reqkind magic
203     
204     set f [open $database_fn.new w]
205     puts $f $magic
206
207     write_database_header/$reqkind $f
208
209     set ol {}
210     foreach bm [array names database] {
211         lappend ol [format_database_entry/$reqkind $bm $database($bm)]
212     }
213     foreach o [lsort $ol] {
214         puts $f $o
215     }
216     puts $f "."
217     close $f
218     file rename -force $database_fn.new $database_fn
219 }
220
221 proc required/char {} {
222     global mulrows glyphsdone unk_l unk_r unk_contexts rows
223     
224     must_gets stdin l
225
226     manyset [lrange $l 0 3] unk_l unk_r unk_contexts
227     set glyphsdone [lrange $l 3 end]
228     debug "GOT $l"
229
230     char_read_xpm stdin
231
232     resize_widgets_core
233     foreach w {0 1} {
234         .d.mi.csr_$w configure -height $mulrows
235     }
236     set maxh 0
237     foreach {min max contexts got} $glyphsdone {
238         show_context maxh $min $contexts
239     }
240     show_context maxh $unk_l $unk_contexts
241     .d.ctx configure -height $maxh
242     pack forget .d.pe
243     pack .d.csr -side top -before .d.mi
244     pack .d.got .d.ctx -side top -after .d.mi
245
246     read_database "./#local-char$rows#.txt"
247     draw_glyphsdone
248     startup_cursor
249 }
250
251 #========== PIXMAPS ==========
252
253 #---------- pixmap database read and write ----------
254
255 set database_magic/pixmap {# ypp-sc-tools pctb pixmaps v1}
256
257 proc read_database_header/pixmap {f} { }
258 proc read_database_entry/pixmap {f def} {
259     global database
260
261     set im ""
262     
263     set p3 [db_getsl $f];       append im $p3    "\n"
264     if {[string compare $p3 P3]} { error "$p3 ?" }
265
266     set wh [db_getsl $f];       append im $wh    "\n";   manyset $wh w h
267     set depth [db_getsl $f];    append im $depth "\n"
268
269     for {set y 0} {$y < $h} {incr y} {
270         set line [db_getsl $f]; append im $line  "\n"
271     }
272     set database($im) $def
273 }
274 proc write_database_header/pixmap {f} { puts $f "" }
275 proc format_database_entry/pixmap {im def} {
276     return "$def\n$im"
277 }
278
279 #---------- pixmap display and input handling ----------
280
281 proc foreach_pixmap_col {var body} {
282     global alloptions
283     upvar 1 $var col
284     for {set col 0} {$col < [llength $alloptions]/3} {incr col} {
285         uplevel 1 $body
286     }
287 }
288
289 proc pixmap_select {ncol} {
290     global alloptions
291     debug "PIX SELECT $ncol [llength $alloptions]"
292     foreach_pixmap_col col {
293         if {$col==$ncol} continue
294         .d.pe.grid.l$col selection clear 0 end
295     }
296     pixmap_maybe_ok
297 }
298 proc pixmap_maybe_ok {} {
299     global alloptions pixmap_selcol pixmap_selrow
300     set nsel 0
301     foreach_pixmap_col col {
302         set cs [.d.pe.grid.l$col curselection]
303         set lcs [llength $cs]
304         if {!$lcs} continue
305         incr nsel $lcs
306         set pixmap_selcol $col
307         set pixmap_selrow [lindex $cs 0]
308     }
309     if {$nsel==1} {
310         debug "MAYBE_OK YES col=$pixmap_selcol row=$pixmap_selrow."
311         .d.pe.ok configure -state normal -command pixmap_ok
312     } else {
313         .d.pe.ok configure -state disabled -command {}
314     }
315 }
316 proc pixmap_ok {} {
317     global database ppm pixmap_selcol pixmap_selrow mainkind alloptions
318     foreach_pixmap_col col {
319         .d.pe.grid.l$col configure -state disabled
320     }
321     .d.pe.ok configure -state disabled
322     helptext {{{ Processing }}}
323     manyset [lrange $alloptions [expr {$pixmap_selcol*3}] end] \
324         colname coldesc rows
325     manyset [lrange $rows [expr {$pixmap_selrow*2}] end] \
326         rowname rowdesc
327     set result "$colname - $rowname"
328     debug "UPDATE PIXMAP AS >$result<"
329     set database($ppm) $result
330     write_database
331     done/$mainkind
332 }
333
334 proc required/pixmap {} {
335     global unk_what ppm mulcols alloptions
336     must_gets stdin unk_what
337     debug "GOT pixmap $unk_what"
338     set ppm {}
339     while 1 {
340         must_gets stdin ppml
341         if {![string length $ppml]} break
342         append ppm $ppml "\n"
343     }
344     set data [exec pnmscale 2 << $ppm]
345     image create photo image/main -data $data
346
347     set alloptions [exec ./dictionary-pixmap-options $unk_what]
348
349     read_database "./#local-pixmap#.txt"
350
351     set mulcols [image width image/main]
352     set mulrows [image height image/main]
353     resize_widgets_core
354     place forget .d.mi.csr_0
355     place forget .d.mi.csr_1
356
357     pack forget .d.csr .d.got
358     pack .d.pe -side top -before .d.mi -pady 2
359     #-pady 2 -fill x
360
361     eval destroy [winfo children .d.pe.grid]
362     set col 0; foreach {colname coldesc rows} $alloptions {
363         debug "INIT $col $colname \"$coldesc\""
364         label .d.pe.grid.t$col -text $colname
365         listbox .d.pe.grid.l$col
366         foreach {rowname rowdesc} $rows {
367             debug "INIT $col $colname \"$coldesc\" $rowname \"$rowdesc\""
368             .d.pe.grid.l$col insert end $rowdesc
369         }
370         bind .d.pe.grid.l$col <<ListboxSelect>> [list pixmap_select $col]
371         grid .d.pe.grid.t$col -column $col -row 0
372         grid .d.pe.grid.l$col -column $col -row 1
373         incr col
374     }
375     pixmap_maybe_ok
376     
377     helptext {
378         {{Indicate the meaning of this image, and click OK.}}
379     }
380 }
381
382 #========== UPLOADS TO DICTIONARY SERVER ==========
383
384 proc upload_init_widgets {} {
385     global privacy_setting
386
387     set privacy_setting [upload_status]
388
389     label .privacy.warn -text " Privacy "
390     if {$privacy_setting} {
391         .privacy.warn configure -background yellow -foreground black
392     }
393     label .privacy.overall -text " Upload new dictionary entry:"
394     label .privacy.reference -text " See README.privacy."
395
396     pack .privacy.warn .privacy.overall -side left
397
398     foreach {setting string} {
399         0 {No}
400         1 {Yes, anonymously}
401         2 {Yes, quoting my pirate name.}
402     } {
403         radiobutton .privacy.o$setting -text $string \
404             -value $setting -variable privacy_setting
405         pack .privacy.o$setting -side left
406         if {$setting > $privacy_setting} {
407             .privacy.o$setting configure -state disabled
408         }
409     }
410     pack .privacy.reference -side left
411
412     if {!$privacy_setting} {
413         foreach w [winfo children .privacy] {
414             $w configure -state disabled
415         }
416     }
417 }
418
419 proc upload_status {} {
420     # returns 0, 1, 2 for none, anon, with pirate name
421     global env
422
423     if {![info exists env(YPPSC_PCTB_DICT_SUBMIT)]} { debug a; return 0 }
424     if {![string compare 0 $env(YPPSC_PCTB_DICT_SUBMIT)]} { debug b; return 0 }
425
426     if {![info exists env(YPPSC_PIRATE)]} { return 1 }
427     if {![string length $env(YPPSC_PIRATE)]} { return 1 }
428
429     return 2
430 }
431
432 #========== CHARACTER SET ==========
433
434 #---------- xpm input processor ----------
435
436 proc char_read_xpm {f} {
437     global glyphsdone mul inter rhsmost_max unk_l unk_r mulcols mulrows
438     global cols rows wordmap
439     
440     set o {}
441     set y -3
442     while 1 {
443         must_gets $f l
444         if {![regexp {^"(.*)",$} $l dummy l]} {
445             append o "$l\n"
446             if {[regexp {^\}\;$} $l]} break
447             continue
448         }
449         if {$y==-3} {
450             manyset $l cols rows colours cpp
451             if {$colours!=2 || $cpp!=1} { error "$l ?" }
452
453             set chop_l [expr {$unk_l - 80}]
454             set chop_r [expr {$cols - $unk_l - 100}]
455             if {$chop_l<0} { set chop_l 0 }
456
457             set unk_l [expr {$unk_l - $chop_l}]
458             set unk_r [expr {$unk_r - $chop_l}]
459             set ngd {}
460             foreach {min max contexts got} $glyphsdone {
461                 lappend ngd \
462                     [expr {$min-$chop_l}] \
463                     [expr {$max-$chop_l}] \
464                     $contexts $got
465             }
466             set glyphsdone $ngd
467
468             set realcols $cols
469             set cols [expr {$cols - $chop_l - $chop_r}]
470             debug "NOW cols=$cols chop_l,r=$chop_l,$chop_r rows=$rows\
471                 $unk_l $unk_r $ngd"
472             
473             set mulcols [expr {$cols*$mul+$inter}]
474             set mulrows [expr {$rows*$mul+$inter}]
475             append o "\"$mulcols $mulrows 9 1\",\n"
476             for {set x 0} {$x<$cols} {incr x} { set wordmap($x) 0 }
477         } elseif {$y==-2} { # first pixel
478             append o \
479 "\"+ c #111\",
480 \"a c #800\",
481 \"A c #fcc\",
482 \"b c #00c\",
483 \"B c #fff\",
484 \"u c #000\",
485 \"U c #ff0\",
486 \"q c #000\",
487 \"Q c #ff0\",\n"
488         } elseif {$y==-1} { # 2nd pixel but we've already printed ours
489         } else {
490             set ybit [expr {1<<$y}]
491             set x 0
492             set ol "\"+"
493             set olh $ol
494             if {$chop_r>=0} {
495                 set l [string range $l $chop_l end-$chop_r]
496             } else {
497                 set l [string range $l $chop_l end]
498                 append l [string repeat " " [expr -$chop_r]]
499             }
500             foreach c [split $l ""] {
501                 set how "u"
502                 if {$x >= $unk_l && $x <= $unk_r} {
503                     set how q
504                 } else {
505                     set ab 0
506                     foreach {min max contexts got} $glyphsdone {
507                         set rhsmost_max $max
508                         if {$x >= $min && $x <= $max} {
509                             set how [lindex {a b} $ab]
510                             break
511                         }
512                         set ab [expr {!$ab}]
513                     }
514                 }
515                 switch -exact $c {
516                     " " { set p $how }
517                     "o" {
518                         set p [string toupper $how]
519                         incr wordmap($x) $ybit
520                     }
521                     default { error "$c ?" }
522                 }
523                 append ol "[string repeat $p [expr {$mul-$inter}]][
524                          string repeat + $inter]"
525                 append olh [string repeat + $mul]
526                 incr x
527             }
528             set ole "\",\n"
529             append ol $ole
530             append olh $ole
531             set olhn [string repeat $olh $inter]
532             if {!$y} { append o $olhn }
533             append o [string repeat $ol [expr {$mul-1}]]
534             append o $olhn
535         }
536         incr y
537     }
538     set data [exec xpmtoppm << $o]
539     image create photo image/main -data $data
540 }
541
542 #---------- character set editor display ----------
543
544 proc show_context {maxhv x ctxs} {
545     global mul
546     upvar 1 $maxhv maxh
547     set w .d.ctx.at$x
548     if {[llength $ctxs]==1} { set fg blue } { set fg yellow }
549     label $w -bg black -fg $fg -text [join $ctxs "/\n"] -justify left
550     place $w -x [expr {($x-1)*$mul}] -y 0
551     set wh [winfo reqheight $w]
552     if {$wh > $maxh} { set maxh $wh }
553 }
554
555 proc draw_glyphsdone {} {
556     global glyphsdone mul inter
557     eval destroy [winfo children .d.got]
558     foreach {min max contexts got} $glyphsdone {
559         frame .d.got.m$min -bd 0 -background \#888
560         label .d.got.m$min.l -text "$got" -fg white -bg black -bd 0
561         pack .d.got.m$min.l -padx 1 -pady 1
562         place .d.got.m$min -x [expr {$min*$mul+$inter}] -y 0
563     }
564 }
565
566 proc startup_cursor {} {
567     global cur_already cur_mode cur_0 cur_1 last_ht
568     global glyphsdone unk_l unk_r
569     
570     set cur_already [expr {[llength $glyphsdone]/4-1}]
571     set cur_mode 1 ;# one of:   0 1 already text
572
573     set cur_0 $unk_l
574     set cur_1 [expr {$unk_r+1}]
575
576     recursor
577 }
578
579 #---------- character set runtime display and keystroke handling ----------
580
581 proc recursor/0 {} { recursor//01 0 }
582 proc recursor/1 {} { recursor//01 1 }
583 proc recursor//01 {z1} {
584     global mul rhsmost_max cols glyphsdone
585     upvar #0 cur_$z1 cur
586     .d.csr.csr.l configure -text {adjust}
587     place .d.csr.csr -x [expr {$cur*$mul - 7}]
588     bind_key space { othercursor }
589     bind_leftright_q cur_$z1 0 [expr {$cols-1}]
590     if {[llength $glyphsdone]} {
591         bind_key BackSpace { set cur_mode already; recursor }
592     } else {
593         bind_key BackSpace {}
594     }
595     bind_key Return {
596         if {$cur_0 != $cur_1} {
597             .d.csr.csr.e delete 0 end
598             set cur_mode text
599             recursor
600         }
601     }
602     helptext {
603         {{<- ->}   {move cursor, adjusting area to define}}
604         {Space     {switch to moving other cursor}}
605         {Return    {confirm location, enter letter(s)}}
606         {Backspace {switch to correcting earlier ocr}}
607         {Q         {quit and abandon OCR run}}
608     }
609 }
610 proc othercursor {} {
611     global cur_mode
612     set cur_mode [expr {!$cur_mode}]
613     recursor
614 }
615
616 proc recursor/text {} {
617     helptext {
618         {Return   {confirm entry of new glyph}}
619         {Escape   {abandon entry}}
620     }
621     unbind_all_keys
622     .d.csr.csr.l configure -text {define:}
623     pack .d.csr.csr.e -side left
624     focus .d.csr.csr.e
625     bind_key Return {
626         set strq [.d.csr.csr.e get]
627         if {[regexp -line {^(?:[!-[]|[]-~]|\\\\|\\x[0-9a-f]{2})+} $strq]} {
628             RETURN_RESULT DEFINE "$cur_0 $cur_1 $strq"
629         }
630     }
631     bind_key Escape {
632         bind_key Escape {}
633         pack forget .d.csr.csr.e
634         set cur_mode 1
635         recursor
636     }
637 }
638
639 proc recursor/already {} {
640     global mul
641     global glyphsdone
642     global cur_already mul
643     global glyphsdone cur_already mul
644     .d.csr.csr.l configure -text {correct}
645     set rmax [lindex $glyphsdone [expr {$cur_already*4}]]
646     place .d.csr.csr -x [expr {$rmax*$mul-3}]
647     bind_key Return {}
648     bind_leftright_q cur_already 0 [expr {[llength $glyphsdone]/4-1}]
649     bind_key space { bind_key Delete {}; set cur_mode 1; recursor }
650     bind_key Delete {
651         RETURN_RESULT DELETE [lrange $glyphsdone \
652                                   [expr $cur_already*4] \
653                                   [expr $cur_already*4+2]]
654     }
655     helptext {
656         {{<- ->}   {move cursor, selecting glyph to correct}}
657         {Del       {clear this glyph from the recognition database}}
658         {Space     {switch to selecting area to define as new glyph}}
659         {Q         {quit and abandon OCR run}}
660     }
661 }
662
663 proc bind_leftright_q {var min max} {
664     bind_key Left  [list leftright $var $min $max -1]
665     bind_key Right [list leftright $var $min $max +1]
666     bind_key q     {
667         puts stderr "\nCharacter resolver quitting as you requested."
668         exit 1
669     }
670 }
671 proc leftright {var min max inc} {
672     upvar #0 $var v
673     set vnew $v
674     incr vnew $inc
675     if {$vnew < $min || $vnew > $max} return
676     set v $vnew
677     recursor
678 }
679
680 proc recursor {} {
681     global csrh cur_mode cur_0 cur_1 mul
682     foreach z1 {0 1} {
683         place .d.mi.csr_$z1 -y 0 -x [expr {[set cur_$z1] * $mul}]
684     }
685     recursor/$cur_mode
686 }
687
688 #---------- character database read and write ----------
689
690 # OUT OF DATE
691 # database format:
692 # series of glyphs:
693 #   <context> <ncharacters> <hex>...
694 #   width
695 #   <hex-bitmap>
696
697 # $database($context 0x<bits> 0x<bits>...) = $hex
698
699 set database_magic/char {# ypp-sc-tools pctb font v1}
700     
701 proc read_database_header/char {f} {
702     global rows
703     if {([db_getsl $f])+0 != $rows} { error "wrong h ?" }
704 }
705 proc read_database_entry/char {f context} {
706     global database
707     set bm $context
708     set strq [db_getsl $f]
709     while 1 {
710         set l [db_getsl $f]
711         if {![string length $l]} break
712         lappend bm [format %x 0x$l]
713     }
714     set database($bm) $strq
715 }
716
717 proc write_database_header/char {f} {
718     global rows
719     puts $f "$rows\n"
720 }
721 proc format_database_entry/char {bm strq} {
722     global database rows
723     set o "[lindex $bm 0]\n$strq\n"
724     foreach x [lrange $bm 1 end] { append o "$x\n" }
725     return $o
726 }
727
728 proc dbkey {ctx l r} {
729     global wordmap
730     set bm $ctx
731     for {set x $l} {$x <= $r} {incr x} {
732         lappend bm [format %x $wordmap($x)]
733     }
734     return $bm
735 }
736
737 proc update_database/DEFINE {c0 c1 strq} {
738     global glyphsdone unk_l unk_contexts wordmap database
739     if {$c0 > $c1} { manyset [list $c0 $c1] c1 c0 }
740     if {$c0 == $unk_l} {
741         set ncontexts $unk_contexts
742     } else {
743         foreach {l r contexts got} $glyphsdone {
744             if {$l==$c0} { set ncontexts $contexts; break }
745         }
746         if {![info exists ncontexts]} {
747             puts stderr "must start at letter LHS!"
748             return
749         }
750     }
751     incr c1 -1
752     foreach c $ncontexts {
753         set bm [dbkey $c $c0 $c1]
754         set database($bm) $strq
755     }
756     write_database
757 }
758
759 proc update_database/DELETE {l r ctxs} {
760     global database
761     foreach ctx $ctxs {
762         set bm [dbkey $ctx $l $r]
763         catch { unset database($bm) }
764     }
765     write_database
766 }
767     
768 proc RETURN_RESULT {how what} {
769     global mainkind
770     place forget .d.csr.csr
771     pack forget .d.csr.csr.e
772     helptext {{{ Processing }}}
773     unbind_all_keys
774     update idletasks
775     debug "$how $what"
776     eval update_database/$how $what
777     done/$mainkind
778 }
779
780 #========== server for approving updates ==========
781
782 proc remote-serv-log {dict pirate file event} {
783     global remoteserv_logf
784     set t [clock format [clock seconds] -format {%Y-%m-%d %H:%M:%S %Z}]
785     set s [format "%s %-6s %-31s %s %s\n" \
786                $t $dict $pirate [file tail $file] $event]
787     puts -nonewline $remoteserv_logf $s
788 }
789
790 proc remote-serv/list {} {
791     global dropdir
792     foreach file [glob -nocomplain -type f -directory $dropdir _update.*.rdy] {
793         puts yes
794         puts $file
795         set f [open $file]
796         set d [read $f]
797         close $f
798         puts_counted stdout d
799     }
800     puts end
801 }
802
803 proc remote-serv/take {yesno file dict} {
804     global dropdir dictdir rows reqkind database
805     set rows ""
806     debug "TAKE [list $yesno $file $dict]"
807     read_counted stdin pirate
808     read_counted stdin key
809     read_counted stdin val
810
811     must_gets_exactly stdin confirmed
812
813     if {![string compare pixmap $dict]} {
814         set reqkind pixmap
815         debug "DICT PIXMAP"
816     } elseif {[regexp {^(char)([1-9]\d*)$} $dict dummy reqkind rows]} {
817         debug "DICT CHAR rqk=$reqkind r=$rows."
818     } else {
819         error "$dict ?"
820     }
821     
822     if {$yesno} {
823         read_database $dictdir/master-$dict.txt
824         set database($key) $val
825         write_database
826         set desc approve
827     } else {
828         set desc reject
829     }
830     remote-serv-log $dict $pirate $file "$desc $reqkind $rows"
831     file delete -force $file
832
833     puts done
834 }
835
836 proc remote-serv/noop {} {
837     puts ok
838 }
839
840 set remoteserv_banner {ypp-sc-tools pctb remote-server v1}
841
842 proc main/remoteserv {} {
843     global argv dropdir remoteserv_banner remoteserv_logf dictdir
844     manyset $argv dropdir dictdir
845     puts $remoteserv_banner
846     set remoteserv_logf [open $dropdir/_dict.log a]
847     fconfigure $remoteserv_logf -buffering line
848     while 1 {
849         flush stdout
850         if {[gets stdin l] < 0} break
851         eval remote-serv/$l
852     }
853 }
854
855 #========== updates approver ==========
856
857 proc puts_server {s} {
858     global server
859     debug ">> $s"
860     puts $server $s
861 }
862 proc must_gets_server {lv} {
863     upvar 1 $lv l
864     global server
865     must_gets $server l
866     debug "<< $l"
867 }
868
869 proc must_gets_exactly_server {expected} {
870     must_gets_server got
871     if {[string compare $expected $got]} { error "$expected $got ?" }
872 }
873
874 proc regsub-data {exp subspec args} {
875     global data
876     if {![eval regsub $args -- [list $exp $data $subspec data]]} {
877         error "$exp >$data< ?"
878     }
879 }
880
881 proc chop_counted {var} {
882     upvar 1 $var val
883     global data
884     if {![regexp {^(0|[1-9]\d*)\n} $data dummy l]} { error "$data ?" }
885     regsub-data {^.*\n} {} -line
886     set val [string range $data 0 [expr {$l-1}]]
887     set data [string range $data $l end]
888     debug "CHOP_COUNTED $l $var"
889     regsub-data {^\n} {}
890 }
891
892 proc approve_decompose_data {specdata} {
893     global data
894     set data $specdata
895     
896     regsub-data {^ypp-sc-tools dictionary update v1\n} {}
897     uplevel 1 chop_counted pirate
898     uplevel 1 chop_counted dict
899     uplevel 1 chop_counted ctx
900     uplevel 1 chop_counted def
901     uplevel 1 chop_counted image
902     uplevel 1 chop_counted key
903     uplevel 1 chop_counted val
904
905     return [uplevel 1 {list $dict $def $image}]
906 }
907
908 proc approve_compare {fd1 fd2} {
909     manyset $fd1 file data; set sv1 [approve_decompose_data $data]
910     manyset $fd2 file data; set sv2 [approve_decompose_data $data]
911     return [string compare $sv1 $sv2]
912 }
913
914 proc approve_showentry {ix file specdata} {
915     global approve_ixes
916     
917     approve_decompose_data $specdata
918
919     set wb .app.e$ix
920
921     frame $wb-inf
922     label $wb-inf.who -text $pirate
923
924     entry $wb-inf.file -font fixed -relief flat
925     $wb-inf.file insert end [file tail $file]
926     $wb-inf.file configure -state readonly -width -1
927
928     pack $wb-inf.who $wb-inf.file -side top
929
930     frame $wb-def
931     label $wb-def.scope -text "$dict $ctx"
932     label $wb-def.def -text $def
933     pack $wb-def.scope $wb-def.def -side bottom
934
935     set ppm [exec pnmscale 2 << $image]
936     image create photo approve/$ix -data $ppm
937     label $wb-image -image approve/$ix -bd 2 -relief sunken
938
939     frame $wb-act
940     button $wb-act.rej -text Reject -command [list approve_reject $ix]
941     pack $wb-act.rej
942
943     grid $wb-def $wb-image $wb-act $wb-inf -padx 3
944     grid configure $wb-image -ipadx 3 -ipady 3 -sticky w
945
946     lappend approve_ixes $ix
947 }
948
949 proc approve_approve_reject_one {ix yesno} {
950     global approve_list server
951     manyset [lindex $approve_list $ix] file tdata
952     approve_decompose_data $tdata
953     puts_server "take $yesno $file $dict"
954     puts_counted $server pirate
955     puts_counted $server key
956     puts_counted $server val
957     puts_server confirmed
958     flush $server
959     must_gets_exactly_server done
960 }
961
962 proc approve_check_server {} {
963     global server
964     puts_server noop
965     flush $server
966     must_gets_exactly_server ok
967 }
968
969 proc approve_reject {ix} {
970     approve_check_server
971     approve_approve_reject_one $ix 0
972     approve_fetch_list
973 }
974
975 proc approve_these {} {
976     global approve_ixes
977     approve_check_server
978     foreach ix $approve_ixes { approve_approve_reject_one $ix 1 }
979     approve_fetch_list
980 }
981
982 proc approve_fetch_list {} {
983     global server approve_list
984     set approve_list {}
985     puts_server list
986     flush $server
987     while 1 {
988         must_gets_server more
989         switch -exact $more {
990             yes { }
991             end { break }
992             default { error "$more ?" }
993         }
994         must_gets_server file
995         read_counted $server data
996         lappend approve_list [list $file $data]
997     }
998
999     if {![llength $approve_list]} { puts "Nothing (more) to approve."; exit 0 }
1000
1001     set approve_list [lsort -command approve_compare $approve_list]
1002     approve_show_page 0
1003 }
1004
1005 proc main/approve {} {
1006     global argv server remoteserv_banner data approve_list approve_page
1007     global userhost directory dictdir debug
1008
1009     if {[llength $argv] != 3} { error "wrong # args" }
1010     manyset $argv userhost directory dictdir
1011     set cmd [list tclsh $directory/dictionary-manager]
1012     if {$debug} { lappend cmd --debug-server }
1013     lappend cmd --remote-server-1 $directory $dictdir
1014     switch -glob $userhost {
1015         {} { }
1016         {* *} { set cmd $userhost }
1017         * { set cmd [append [list ssh $userhost] $cmd] }
1018     }
1019     lappend cmd 2>@ stderr
1020     set server [open |$cmd r+]
1021     must_gets_exactly_server $remoteserv_banner
1022
1023     button .left -text {<<} -command {approve_show_page -1}
1024     button .right -text {>>} -command {approve_show_page +1}
1025
1026     label .title -text {}
1027     frame .app -bd 2 -relief groove
1028     button .ok -text "Approve These" -command approve_these
1029     pack .title .app -side top
1030     pack .left -side left
1031     pack .right -side right
1032     pack .ok -side bottom
1033
1034     set approve_page 0
1035     approve_fetch_list
1036 }
1037
1038 proc approve_show_page {delta} {
1039     global approve_page approve_ixes approve_list userhost directory dictdir
1040
1041     eval destroy [winfo children .app]
1042     set approve_ixes {}
1043
1044     set per_page 10
1045     incr approve_page $delta
1046
1047     set ll [llength $approve_list]
1048     set npages [expr {($ll+$per_page-1)/$per_page}]
1049     if {$approve_page >= $npages} { incr approve_page -1 }
1050
1051     set page_start [expr {$approve_page*$per_page}]
1052     set page_end [expr {$page_start+$per_page-1}]
1053     
1054     for {set ix $page_start} {$ix < $ll && $ix <= $page_end} {incr ix} {
1055         set fd [lindex $approve_list $ix]
1056         eval approve_showentry $ix $fd
1057     }
1058
1059     .title configure -text \
1060  "$userhost\n$directory => $dictdir\nPage [expr {$approve_page+1}]/$npages"
1061
1062     .left configure -state disabled
1063     .right configure -state disabled
1064     if {$approve_page>0} { .left configure -state normal }
1065     if {$approve_page<$npages-1} { .right configure -state normal }
1066 }
1067
1068 #========== main program ==========
1069
1070 proc main/default {} {
1071     puts stderr "Do not run this program directly."
1072     exit 12
1073 }
1074 proc done/default {} {
1075 }
1076
1077 proc required {} {
1078     global reqkind
1079
1080     fileevent stdin readable {}
1081     fconfigure stdin -blocking yes
1082     
1083     if {[gets stdin reqkind]<0} {
1084         if {[eof stdin]} { fconfigure stdin -blocking yes; exit 0 }
1085         return
1086     }
1087     init_widgets
1088
1089     required/$reqkind
1090 }
1091
1092 proc main/automatic {} {
1093     fconfigure stdin -blocking no
1094     fileevent stdin readable required
1095 }
1096 proc done/automatic {} {
1097     exec sh -c {printf \\0 >&4}
1098     main/automatic
1099 }
1100
1101 proc debug {m} { }
1102
1103 set mainkind default
1104 set ai 0
1105 set debug 0
1106 foreach arg $argv {
1107     incr ai
1108     switch -exact -- $arg {
1109         {--debug}           { set debug 1 }
1110         {--debug-server}    { proc debug {m} { puts stderr "DICT-MGR-SVR $m" }}
1111         {--noop-arg}        { }
1112         {--approve-updates} { set mainkind approve; break }
1113         {--automatic-1}     { set mainkind automatic; break }
1114         {--remote-server-1} { set mainkind remoteserv; break }
1115         {--automatic*} - {--remote-server}
1116                             { error "incompatible versions - install problem" }
1117         default             { error "huh $argv ?" }
1118     }
1119 }
1120 if {$debug} {
1121     proc debug {m} { puts stderr "DICT-MGR $m" }
1122 }
1123 set argv [lrange $argv $ai end]
1124
1125 main/$mainkind