chiark / gitweb /
Merge branch 'master' of ijackson@chiark:things/ypp-sc-tools
[ypp-sc-tools.db-live.git] / pctb / yppsc-ocr-resolver
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 proc manyset {list args} {
39     foreach val $list var $args {
40         upvar 1 $var my
41         set my $val
42     }
43 }
44
45
46 #---------- display core ----------
47
48 set mul 6
49 set inter 1
50
51 set gotsh 20
52 set csrh 20
53 set ctxh 20
54
55 proc init_widgets {} {
56     # idempotent
57     global csrh gotsh ctxh
58
59     if {[winfo exists .d]} return
60     
61     frame .d
62
63     image create bitmap image/main
64     label .d.mi -image image/main -borderwidth 0
65
66     frame .d.csr -bg black -height $csrh
67     frame .d.got -bg black -height $gotsh
68     frame .d.ctx -bg black
69
70     image create bitmap image/cursor -data \
71 {#define csr_width 11
72 #define csr_height 11
73 static unsigned char csr_bits[] = {
74    0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x21, 0x04, 0x22, 0x02, 0x25, 0x05,
75    0xaa, 0x02, 0x74, 0x01, 0xa8, 0x00, 0x70, 0x00, 0x20, 0x00};
76 }
77
78     frame .d.csr.csr
79     label .d.csr.csr.l -image image/cursor -compound left
80     entry .d.csr.csr.e -bd 0
81     pack .d.csr.csr.l -side left
82
83     frame .d.mi.csr_0 -bg white -width 1
84     frame .d.mi.csr_1 -bg white -width 1
85     frame .d.pe
86     frame .d.pe.grid
87     button .d.pe.ok -text OK
88     pack .d.pe.grid .d.pe.ok -side left
89
90     pack .d.mi .d.got .d.ctx -side top
91     pack .d
92
93     frame .help
94     pack .help
95 }
96
97 proc show_context {maxhv x ctxs} {
98     global mul
99     upvar 1 $maxhv maxh
100     set w .d.ctx.at$x
101     if {[llength $ctxs]==1} { set fg blue } { set fg yellow }
102     label $w -bg black -fg $fg -text [join $ctxs "/\n"] -justify left
103     place $w -x [expr {($x-1)*$mul}] -y 0
104     set wh [winfo reqheight $w]
105     if {$wh > $maxh} { set maxh $wh }
106 }
107
108 proc resize_widgets_core {} {
109     global mulcols mulrows csrh gotsh ctxh glyphsdone
110     global unk_l unk_contexts
111     
112     foreach w {.d.csr .d.got .d.ctx} {
113         $w configure -width $mulcols
114     }
115
116     eval destroy [winfo children .d.ctx]
117 }
118
119
120 #---------- xpm input processor ----------
121
122 proc must_gets {f lvar} {
123     upvar 1 $lvar l
124     if {[gets $f l] < 0} { error "huh?" }
125 }
126
127 proc read_xpm {f} {
128     global glyphsdone mul inter rhsmost_max unk_l unk_r mulcols mulrows
129     global cols rows wordmap
130     
131     set o {}
132     set y -3
133     while 1 {
134         must_gets $f l
135         if {![regexp {^"(.*)",$} $l dummy l]} {
136             append o "$l\n"
137             if {[regexp {^\}\;$} $l]} break
138             continue
139         }
140         if {$y==-3} {
141             manyset $l cols rows colours cpp
142             if {$colours!=2 || $cpp!=1} { error "$l ?" }
143
144             set chop_l [expr {$unk_l - 80}]
145             set chop_r [expr {$cols - $unk_l - 100}]
146             if {$chop_l<0} { set chop_l 0 }
147
148             set unk_l [expr {$unk_l - $chop_l}]
149             set unk_r [expr {$unk_r - $chop_l}]
150             set ngd {}
151             foreach {min max contexts got} $glyphsdone {
152                 lappend ngd \
153                     [expr {$min-$chop_l}] \
154                     [expr {$max-$chop_l}] \
155                     $contexts $got
156             }
157             set glyphsdone $ngd
158
159             set realcols $cols
160             set cols [expr {$cols - $chop_l - $chop_r}]
161             debug "NOW cols=$cols chop_l,r=$chop_l,$chop_r rows=$rows\
162                 $unk_l $unk_r $ngd"
163             
164             set mulcols [expr {$cols*$mul+$inter}]
165             set mulrows [expr {$rows*$mul+$inter}]
166             append o "\"$mulcols $mulrows 9 1\",\n"
167             for {set x 0} {$x<$cols} {incr x} { set wordmap($x) 0 }
168         } elseif {$y==-2} { # first pixel
169             append o \
170 "\"+ c #111\",
171 \"a c #800\",
172 \"A c #fcc\",
173 \"b c #00c\",
174 \"B c #fff\",
175 \"u c #000\",
176 \"U c #ff0\",
177 \"q c #000\",
178 \"Q c #ff0\",\n"
179         } elseif {$y==-1} { # 2nd pixel but we've already printed ours
180         } else {
181             set ybit [expr {1<<$y}]
182             set x 0
183             set ol "\"+"
184             set olh $ol
185             if {$chop_r>=0} {
186                 set l [string range $l $chop_l end-$chop_r]
187             } else {
188                 set l [string range $l $chop_l end]
189                 append l [string repeat " " [expr -$chop_r]]
190             }
191             foreach c [split $l ""] {
192                 set how "u"
193                 if {$x >= $unk_l && $x <= $unk_r} {
194                     set how q
195                 } else {
196                     set ab 0
197                     foreach {min max contexts got} $glyphsdone {
198                         set rhsmost_max $max
199                         if {$x >= $min && $x <= $max} {
200                             set how [lindex {a b} $ab]
201                             break
202                         }
203                         set ab [expr {!$ab}]
204                     }
205                 }
206                 switch -exact $c {
207                     " " { set p $how }
208                     "o" {
209                         set p [string toupper $how]
210                         incr wordmap($x) $ybit
211                     }
212                     default { error "$c ?" }
213                 }
214                 append ol "[string repeat $p [expr {$mul-$inter}]][
215                          string repeat + $inter]"
216                 append olh [string repeat + $mul]
217                 incr x
218             }
219             set ole "\",\n"
220             append ol $ole
221             append olh $ole
222             set olhn [string repeat $olh $inter]
223             if {!$y} { append o $olhn }
224             append o [string repeat $ol [expr {$mul-1}]]
225             append o $olhn
226         }
227         incr y
228     }
229     set data [exec xpmtoppm << $o]
230     image create photo image/main -data $data
231 }
232
233
234 #---------- per-invocation display ----------
235
236 proc draw_glyphsdone {} {
237     global glyphsdone mul inter
238     eval destroy [winfo children .d.got]
239     foreach {min max contexts got} $glyphsdone {
240         frame .d.got.m$min -bd 0 -background \#888
241         label .d.got.m$min.l -text "$got" -fg white -bg black -bd 0
242         pack .d.got.m$min.l -padx 1 -pady 1
243         place .d.got.m$min -x [expr {$min*$mul+$inter}] -y 0
244     }
245 }
246
247 proc startup_cursor {} {
248     global cur_already cur_mode cur_0 cur_1 last_ht
249     global glyphsdone unk_l unk_r
250     
251     set cur_already [expr {[llength $glyphsdone]/4-1}]
252     set cur_mode 1 ;# one of:   0 1 already text
253
254     set cur_0 $unk_l
255     set cur_1 [expr {$unk_r+1}]
256
257     recursor
258 }
259
260
261 #---------- runtime display and keystroke handling ----------
262
263 set last_ht {}
264
265 proc helptext {t} {
266     global last_ht
267     if {![string compare $t $last_ht]} return
268     eval destroy [grid slaves .help]
269     set y 0; foreach l $t {
270         set x 0; foreach c $l {
271             set w .help.at${x}x${y}
272             label $w -text $c
273             grid $w -row $y -column $x -padx 5
274             incr x
275         }
276         incr y
277     }
278     set last_ht $t
279 }
280
281 proc recursor/0 {} { recursor//01 0 }
282 proc recursor/1 {} { recursor//01 1 }
283 proc recursor//01 {z1} {
284     global mul rhsmost_max cols glyphsdone
285     upvar #0 cur_$z1 cur
286     .d.csr.csr.l configure -text {adjust}
287     place .d.csr.csr -x [expr {$cur*$mul - 7}]
288     bind_key space { othercursor }
289     bind_leftright_q cur_$z1 0 [expr {$cols-1}]
290     if {[llength $glyphsdone]} {
291         bind_key Tab { set cur_mode already; recursor }
292     } else {
293         bind_key Tab {}
294     }
295     bind_key Return {
296         if {$cur_0 != $cur_1} {
297             .d.csr.csr.e delete 0 end
298             set cur_mode text
299             recursor
300         }
301     }
302     helptext {
303         {{<- ->}   {move cursor, adjusting area to define}}
304         {Space     {switch to moving other cursor}}
305         {Return    {confirm location, enter letter(s)}}
306         {Tab       {switch to correcting earlier ocr}}
307         {Q         {quit and abandon OCR run}}
308     }
309 }
310 proc othercursor {} {
311     global cur_mode
312     set cur_mode [expr {!$cur_mode}]
313     recursor
314 }
315
316 proc recursor/text {} {
317     helptext {
318         {Return   {confirm entry of new glyph}}
319         {Escape   {abandon entry}}
320     }
321     unbind_all_keys
322     .d.csr.csr.l configure -text {define:}
323     pack .d.csr.csr.e -side left
324     focus .d.csr.csr.e
325     bind_key Return {
326         set strq [.d.csr.csr.e get]
327         if {[regexp {^(?:[!-[]|[]-~]|\\\\|\\x[0-9a-f]{2})+} $strq]} {
328             RETURN_RESULT DEFINE "$cur_0 $cur_1 $strq"
329         }
330     }
331     bind_key Escape {
332         bind_key Escape {}
333         pack forget .d.csr.csr.e
334         set cur_mode 1
335         recursor
336     }
337 }
338
339 proc recursor/already {} {
340     global mul
341     global glyphsdone
342     global cur_already mul
343     global glyphsdone cur_already mul
344     .d.csr.csr.l configure -text {correct}
345     set rmax [lindex $glyphsdone [expr {$cur_already*4}]]
346     place .d.csr.csr -x [expr {$rmax*$mul-3}]
347     bind_key Return {}
348     bind_key space {}
349     bind_leftright_q cur_already 0 [expr {[llength $glyphsdone]/4-1}]
350     bind_key Tab { bind_key Delete {}; set cur_mode 1; recursor }
351     bind_key Delete {
352         RETURN_RESULT DELETE [lrange $glyphsdone \
353                                   [expr $cur_already*4] \
354                                   [expr $cur_already*4+2]]
355     }
356     helptext {
357         {{<- ->}   {move cursor, selecting glyph to correct}}
358         {Del       {clear this glyph from the recognition database}}
359         {Tab       {switch to selecting area to define as new glyph}}
360         {Q         {quit and abandon OCR run}}
361     }
362 }
363
364 proc bind_key {k proc} {
365     global keybindings
366     bind . <Key-$k> $proc
367     set keybindings($k) [expr {!![string length $proc]}]
368 }
369 proc unbind_all_keys {} {
370     global keybindings
371     foreach k [array names keybindings] { bind_key $k {} }
372 }
373
374 proc bind_leftright_q {var min max} {
375     bind_key Left  [list leftright $var $min $max -1]
376     bind_key Right [list leftright $var $min $max +1]
377     bind_key q     {
378         puts stderr "\nCharacter resolver quitting as you requested."
379         exit 1
380     }
381 }
382 proc leftright {var min max inc} {
383     upvar #0 $var v
384     set vnew $v
385     incr vnew $inc
386     if {$vnew < $min || $vnew > $max} return
387     set v $vnew
388     recursor
389 }
390
391 proc recursor {} {
392     global csrh cur_mode cur_0 cur_1 mul
393     foreach z1 {0 1} {
394         place .d.mi.csr_$z1 -y 0 -x [expr {[set cur_$z1] * $mul}]
395     }
396     recursor/$cur_mode
397 }
398
399
400 #---------- database read and write ----------
401
402 # OUT OF DATE
403 # database format:
404 # series of glyphs:
405 #   <context> <ncharacters> <hex>...
406 #   width
407 #   <hex-bitmap>
408
409 # $database($context 0x<bits> 0x<bits>...) = $hex
410
411 set database_header {# ypp-sc-tools pctb font v1}
412
413 proc db_getsl {f} {
414     if {[gets $f l] < 0} { error "unexpected db eof" }
415     return $l
416 }
417     
418 proc read_database {} {
419     global database database_header rows database_fn
420     catch { unset database }
421     set database_fn ./charset-$rows.txt
422     if {![file exists $database_fn]} return
423     set f [open $database_fn r]
424     if {[string compare [db_getsl $f] $database_header]} { error "$l ?" }
425     if {([db_getsl $f])+0 != $rows} { error "wrong h ?" }
426     while 1 {
427         set context [db_getsl $f]
428         if {![string length $context]} continue
429         if {[regexp {^\#} $context]} continue
430         if {![string compare . $context]} break
431
432         set bm $context
433         set strq [db_getsl $f]
434         while 1 {
435             set l [db_getsl $f]
436             if {![string length $l]} break
437             lappend bm [format %x 0x$l]
438         }
439         set database($bm) $strq
440     }
441     close $f
442 }
443
444 proc write_database {} {
445     global database rows database_fn database_header
446     set ol {}
447     foreach bm [array names database] {
448         set strq $database($bm)
449         set o "[lindex $bm 0]\n$strq\n"
450         foreach x [lrange $bm 1 end] { append o "$x\n" }
451         
452         lappend ol $o
453     }
454     set f [open $database_fn.new w]
455     puts $f "$database_header\n$rows\n"
456     foreach o [lsort $ol] {
457         puts $f $o
458     }
459     puts $f "."
460     close $f
461     file rename -force $database_fn.new $database_fn
462 }
463
464 proc dbkey {ctx l r} {
465     global wordmap
466     set bm $ctx
467     for {set x $l} {$x <= $r} {incr x} {
468         lappend bm [format %x $wordmap($x)]
469     }
470     return $bm
471 }
472
473 proc update_database/DEFINE {c0 c1 strq} {
474     global glyphsdone unk_l unk_contexts wordmap database
475     if {$c0 > $c1} { manyset [list $c0 $c1] c1 c0 }
476     if {$c0 == $unk_l} {
477         set ncontexts $unk_contexts
478     } else {
479         foreach {l r contexts got} $glyphsdone {
480             if {$l==$c0} { set ncontexts $contexts; break }
481         }
482         if {![info exists ncontexts]} {
483             puts stderr "must start at letter LHS!"
484             return
485         }
486     }
487     incr c1 -1
488     foreach c $ncontexts {
489         set bm [dbkey $c $c0 $c1]
490         set database($bm) $strq
491     }
492     write_database
493 }
494
495 proc update_database/DELETE {l r ctxs} {
496     global database
497     foreach ctx $ctxs {
498         set bm [dbkey $ctx $l $r]
499         catch { unset database($bm) }
500     }
501     write_database
502 }
503     
504
505 proc RETURN_RESULT {how what} {
506     global mainkind
507     place forget .d.csr.csr
508     pack forget .d.csr.csr.e
509     helptext {{{ Processing }}}
510     unbind_all_keys
511     update idletasks
512     debug "$how $what"
513     eval update_database/$how $what
514     done/$mainkind
515 }
516
517 #---------- main progrm ----------
518
519 proc main/default {} {
520     puts stderr "Do not run this program directly."
521     exit 12
522 }
523 proc done/default {} {
524 }
525
526 proc required {} {
527     global glyphsdone unk_l unk_r unk_contexts
528
529     fileevent stdin readable {}
530     fconfigure stdin -blocking yes
531     
532     if {[gets stdin l]<0} {
533         if {[eof stdin]} { fconfigure stdin -blocking yes; exit 0 }
534         return
535     }
536     init_widgets
537
538     required/$l
539 }
540
541
542 proc foreach_pixmap_col {var body} {
543     global alloptions
544     upvar 1 $var col
545     for {set col 0} {$col < [llength $alloptions]/3} {incr col} {
546         uplevel 1 $body
547     }
548 }
549
550 proc pixmap_select {ncol} {
551     global alloptions
552     debug "PIX SELECT $ncol [llength $alloptions]"
553     foreach_pixmap_col col {
554         if {$col==$ncol} continue
555         .d.pe.grid.l$col selection clear 0 end
556     }
557     pixmap_maybe_ok
558 }
559 proc pixmap_maybe_ok {} {
560     global alloptions pixmap_selcol pixmap_selrow
561     set nsel 0
562     foreach_pixmap_col col {
563         set cs [.d.pe.grid.l$col curselection]
564         incr nsel [llength $cs]
565         set pixmap_selcol $col
566         set pixmap_selrow [lindex $cs 0]
567     }
568     if {$nsel==1} {
569         .d.pe.ok configure -state normal -command pixmap_ok
570     } else {
571         .d.pe.ok configure -state disabled -command {}
572     }
573 }
574 proc pixmap_ok {} {
575     foreach_pixmap_col col {
576         .d.pe.grid.l$col configure -state disabled
577     }
578     .d.pe.ok configure -state disabled
579     helptext {{{ Processing }}}
580 }
581
582 proc required/pixmap {} {
583     global unk_what ppm mulcols alloptions
584     must_gets stdin unk_what
585     debug "GOT pixmap $unk_what"
586     set ppm {}
587     while 1 {
588         must_gets stdin ppml
589         if {![string length $ppml]} break
590         append ppm $ppml "\n"
591     }
592     set data [exec pnmscale 2 << $ppm]
593     image create photo image/main -data $data
594
595     set alloptions [exec ./yppsc-resolver-pixoptions $unk_what]
596
597     #read_database_pixmaps
598
599     set mulcols [image width image/main]
600     set mulrows [image height image/main]
601     resize_widgets_core
602     place forget .d.mi.csr_0
603     place forget .d.mi.csr_1
604     .d.ctx configure -height 0
605     pack forget .d.csr
606     pack .d.pe -side top -before .d.mi -pady 10
607
608     eval destroy [winfo children .d.pe.grid]
609     set col 0; foreach {colname coldesc rows} $alloptions {
610         debug "INIT $col $colname \"$coldesc\""
611         label .d.pe.grid.t$col -text $colname
612         listbox .d.pe.grid.l$col
613         foreach {rowname rowdesc} $rows {
614             debug "INIT $col $colname \"$coldesc\" $rowname \"$rowdesc\""
615             .d.pe.grid.l$col insert end $rowdesc
616         }
617         bind .d.pe.grid.l$col <<ListboxSelect>> [list pixmap_select $col]
618         grid .d.pe.grid.t$col -column $col -row 0
619         grid .d.pe.grid.l$col -column $col -row 1
620         incr col
621     }
622     pixmap_maybe_ok
623     
624     helptext {
625         {{Indicate the correct parse of this image, and click OK.}}
626     }
627 }
628
629 proc required/char {} {
630     global mulrows
631     
632     must_gets stdin l
633
634     manyset [lrange $l 0 3] unk_l unk_r unk_contexts
635     set glyphsdone [lrange $l 3 end]
636     debug "GOT $l"
637
638     read_xpm stdin
639
640     resize_widgets_core
641     foreach w {0 1} {
642         .d.mi.csr_$w configure -height $mulrows
643     }
644     set maxh 0
645     foreach {min max contexts got} $glyphsdone {
646         show_context maxh $min $contexts
647     }
648     show_context maxh $unk_l $unk_contexts
649     .d.ctx configure -height $maxh
650     pack forget .d.pe
651     pack .d.csr -side top -before .d.mi
652
653     read_database
654     draw_glyphsdone
655     startup_cursor
656 }
657
658 proc main/automatic {} {
659     fconfigure stdin -blocking no
660     fileevent stdin readable required
661 }
662 proc done/automatic {} {
663     exec sh -c {printf \\0 >&4}
664     main/automatic
665 }
666
667 proc debug {m} { }
668
669 set mainkind default
670 foreach arg $argv {
671     switch -exact -- $arg {
672         {--debug}        { proc debug {m} { puts stderr "SHOW-THING $m" } }
673         {--noop-arg}     { }
674         {--automatic-1}  { set mainkind automatic }
675         {--automatic*}   { error "incompatible versions - install problem" }
676         default          { error "huh $argv ?" }
677     }
678 }
679
680 main/$mainkind