chiark / gitweb /
where-vessels: Ownership smasher is gridded
[ypp-sc-tools.db-test.git] / yarrg / where-vessels
1 #!/usr/bin/wish
2 # show your vessels on a map
3
4 # This is part of ypp-sc-tools, a set of third-party tools for assisting
5 # players of Yohoho Puzzle Pirates.
6 #
7 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
8 #
9 # This program is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 #
22 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
23 # are used without permission.  This program is not endorsed or
24 # sponsored by Three Rings.
25
26
27
28 source yarrglib.tcl
29 source panner.tcl
30 package require http
31
32 #---------- general utilities ----------
33
34 set debug 0
35 proc debug {m} {
36     global debug
37     if {$debug} { puts "DEBUG $m" }
38 }
39
40 proc badusage {m} {
41     puts stderr "where-vessels: bad usage: $m"
42     exit 1
43 }
44
45 proc glset {n val} {
46     upvar #0 $n var
47     set var $val
48 }
49
50 #---------- expecting certain errors ----------
51
52 proc errexpect-setline {lno line} {
53     glset errexpect_lno $lno
54     glset errexpect_line $line
55 }
56
57 proc errexpect-error {m} {
58     global errexpect_line errexpect_lno
59     error $m "$errexpect_line\n" [list YARRG-ERREXPECT $errexpect_lno]
60 }
61
62 proc errexpect-arrayget {arrayvar key} {
63     upvar 1 $arrayvar av
64     upvar 1 ${arrayvar}($key) v
65     if {[info exists v]} { return $v }
66     errexpect-error "undefined $key"
67 }
68
69 proc errexpect-arrayget-boolean {arrayvar key} {
70     switch -exact [uplevel 1 [list errexpect-arrayget $arrayvar $key]] {
71         true    { return 1 }
72         false   { return 0 }
73         default { errexpect-error "unexpected $key" }
74     }
75 }
76
77 proc errexpect-catch {code} {
78     global errorInfo errorCode
79     set rc [catch {
80         uplevel 1 $code
81     } rv]
82     debug "ERREXPECT CATCH |$rc|$rv|$errorCode|$errorInfo|"
83     if {$rc==1 && ![string compare YARRG-ERREXPECT [lindex $errorCode 0]]} {
84         return [list 1 $rv [lindex $errorCode 1] $errorInfo]
85     } elseif {$rc==0} {
86         return [list 0 $rv]
87     } else {
88         return -code $rc -errorinfo $errorInfo -errorcode $errorCode $rv
89     }
90 }
91
92 #---------- argument parsing ----------
93
94 proc nextarg {} {
95     global ai argv
96     if {$ai >= [llength $argv]} {
97         badusage "option [lindex $argv [expr {$ai-1}]] needs a value"
98     }
99     set v [lindex $argv $ai]
100     incr ai
101     return $v
102 }
103
104 set notes_loc vessel-notes
105 set scraper {./yppedia-ocean-scraper --chart}
106 set info_cache _vessel-info-cache
107 set info_source rsync.yarrg.chiark.net::yarrg/vessel-info
108
109 proc parseargs {} {
110     global ai argv
111     global debug scraper
112     set ai 0
113
114     while {[regexp {^\-} [set arg [lindex $argv $ai]]]} {
115         incr ai
116         switch -exact -- $arg {
117             -- { break }
118             --pirate { glset pirate [string totitle [nextarg]] }
119             --ocean { glset ocean [string totitle [nextarg]] }
120             --clipboard-file { load-clipboard-file [nextarg] }
121             --local-html-dir { lappend scraper --local-html-dir=[nextarg] }
122             --notes { glset notes_loc [nextarg] }
123             --vessel-info-source { glset info_source [nextarg] }
124             --debug { incr debug }
125             default { badusage "unknown option $arg" }
126         }
127     }
128     set argv [lrange $argv $ai end]
129     if {[llength $argv]} { badusage "non-option args not allowed" }
130 }
131
132 proc argdefaults {} {
133     global ocean notes_loc pirate scraper
134     if {![info exists ocean] || ![info exists pirate]} {
135         set cmd {./yarrg --find-window-only --quiet}
136         if {[info exists ocean]} { lappend cmd --ocean $ocean }
137         if {[info exists pirate]} { lappend cmd --pirate $pirate }
138         manyset [split [eval exec $cmd] " "] ocean pirate
139         if {![llength $ocean] || ![llength $pirate]} {
140             error "$ocean $pirate ?"
141         }
142     }
143     lappend scraper $ocean
144 }
145
146
147 #---------- loading and parsing the vessel notes ----------
148
149 proc load-notes {} {
150     global notes_loc notes_data
151     if {[regexp {^\w+\:} $notes_loc]} {
152         update
153         debug "FETCHING NOTES $notes_loc"
154         set req [::http::geturl $notes_loc]
155         switch -glob [::http::status $req].[::http::ncode $req] {
156             ok.200 { }
157             ok.* { error "retrieving vessel-notes: [::http::code $req]" }
158             * { error "Retrieving vessel-notes: [::http::error $req]" }
159         }
160         set newdata [::http::data $req]
161         ::http::cleanup $req
162     } else {
163         debug "READING NOTES $notes_loc"
164         set vn [open $notes_loc]
165         set newdata [read $vn]
166         close $vn
167     }
168     set notes_data $newdata
169 }
170
171 proc parse-notes {} {
172     global notes_data notes
173     catch { unset notes }
174
175     set lno 0
176     foreach l [split $notes_data "\n"] {
177         incr lno
178         errexpect-setline $lno $l
179         set l [string trim $l]
180         if {![string length $l]} continue
181         if {[regexp {^\#} $l]} continue
182         if {![regexp -expanded \
183                   {^ (\d+) (?: \s+([^=]*?) )? \s* =
184                       (?: \s* (\S+)
185                        (?: \s+ (\S+) )?)? $} \
186                   $l dummy vid vname owner note]} {
187               errexpect-error "badly formatted"
188         }
189         set vname [string trim $vname]
190         if {[info exists notes($vid)]} {
191             errexpect-error "duplicate vesselid $vid"
192         }
193         set notes($vid) [list $lno $vname $owner $note]
194     }
195 }
196
197 proc note-info {lno vid name island description} {
198     global note_infos
199     lappend note_infos [list $lno $vid $name $island $description]
200 }
201
202 proc display-note-infos {} {
203     global note_infos note_missings notes
204
205     set nmissing [llength $note_missings]
206     debug "display-note-infos $nmissing [array size notes]"
207
208     if {[llength $note_infos]} {
209         set tiny "[llength $note_infos] warning(s)"
210     } elseif {$nmissing && [array size notes]} {
211         set tiny "$nmissing missing"
212     } else {
213         return
214     }
215
216     set infodata {}
217
218     foreach info $note_infos {
219         manyset $info lno vid name island description
220         append infodata "vessel"
221         append infodata " $vid"
222         if {[string length $name]} { append infodata " $name" }
223         if {[string length $island]} { append infodata " ($island)" }
224         append infodata ": " $description "\n"
225     }
226
227     if {$nmissing} {
228         if {[string length $infodata]} { append infodata "\n" }
229         append infodata "$nmissing vessel(s) not mentioned in notes:\n"
230         set last_island {}
231         foreach info [lsort $note_missings] {
232             manyset $info island name vid
233             if {[string compare $island $last_island]} {
234                 append infodata "# $island:\n"
235                 set last_island $island
236             }
237             append infodata [format "%-9d %-29s =\n" $vid $name]
238         }
239     }
240
241     parser-control-failed-core .cp.ctrl.notes notes \
242         white blue 0 \
243         $tiny \
244         "[llength $note_infos] warning(s);\
245          $nmissing vessel(s) missing" \
246         "Full description of warnings and missing vessels:" \
247         $infodata
248 }
249
250 #---------- vessel properties ----------
251
252 proc info-cache-update {} {
253     global info_source info_cache
254     file mkdir $info_cache
255     exec sh -c "cp -u icons/* $info_cache/."
256
257     if {[string length $info_source]} {
258         set cmdl [list \
259                   rsync -udLKtOzm \
260                   --exclude=*~ --exclude=*.bak --exclude=.* --exclude=*.tmp \
261                   $info_source/ $info_cache 2>@ stderr]
262         debug "INFO-CACHE $cmdl"
263         eval exec $cmdl
264     }
265
266     set f [open $info_cache/vessel-info]
267     glset vessel_class_data [read $f]
268     close $f
269 }
270
271 proc vesselclasses-init {} {
272     global vc_game2code vc_code2abbrev vc_code2full vc_codes
273
274     global vessel_class_data
275     manyset $vessel_class_data classinfos subclassinfos
276
277     set vc_codes {}
278     foreach {game code abbrev full} $classinfos {
279         if {![regexp {^[a-z][a-z]$} $code code]} { error "bad code" }
280         if {![regexp {^[a-z][a-z]$} $abbrev abbrev]} { error "bad abbrev" }
281         lappend vc_codes $code
282         set vc_game2code($game) $code
283         set vc_code2abbrev($code) $abbrev
284         set vc_code2full($code) $full
285         load-icon $abbrev
286     }
287
288     global vsc_code2report
289     global vsc_game2code
290     set vsc_game2code(null) {}
291     set vsc_code2report() Ordinary
292     set vsc_code2report(!) "(Special/L.E.)"
293     foreach {game code full} $subclassinfos {
294         if {![regexp {^[A-Z]$} $code code]} { error "bad code" }
295         set vsc_game2code($game) $code
296         set vsc_code2report($code) $full
297     }
298
299     load-icon atsea
300     set owners {ours dot query}
301     foreach b $owners { load-icon $b }
302     foreach a {battle borrow dot} {
303         load-icon $a
304         foreach b $owners { load-icon-combine $a $b }
305     }
306 }
307
308 proc load-icon {icon} {
309     global info_cache
310     image create bitmap icon/$icon -file $info_cache/$icon.xbm
311 }
312
313 proc load-icon-combine {args} {
314     global info_cache
315     set cmd {}
316     set delim "pnmcat -lr "
317     foreach icon $args {
318         append cmd $delim " <(xbmtopbm $info_cache/$icon.xbm)"
319         set delim " <(pbmmake -white 1 1)"
320     }
321     append cmd " | pbmtoxbm"
322     debug "load-icon-combine $cmd"
323     image create bitmap icon/[join $args +] -data [exec bash -c $cmd]
324 }
325
326 proc code-lockown2icon {lockown} {
327     manyset [split $lockown ""] lock notown
328     set l "
329          [lindex {battle borrow dot} $lock]
330          [lindex {ours dot query {} {} dot} $notown]
331     "
332     if {[llength $l]} { return icon/[join $l +] } { return {} }
333 }
334
335 proc canvas-horiz-stack {xvar xoff y bind type args} {
336     upvar 1 $xvar x
337     upvar 1 canvas canvas
338     set id [eval $canvas create $type [expr {$x+$xoff}] $y $args]
339     set bbox [$canvas bbox $id]
340 #   debug "CANVAS-HORIZ-STACK $type $x $xoff $id $bbox [list $args]"
341     set x [lindex $bbox 2]
342     $canvas bind $id <ButtonPress> $bind
343     return $id
344 }
345
346 proc code2canvas {code canvas x yvar qty qtylen bind} {
347     global vc_code2abbrev
348     upvar 1 $yvar y
349
350     manyset [split $code _] inport class subclass lockown xabbrev
351
352     set stackx $x
353     incr stackx 2
354     set imy [expr {$y+2}]
355
356     if {!$inport} { incr qtylen -1 }
357     if {$qtylen<=0} { set qtylen {} }
358     set qty [format "%${qtylen}s" $qty]
359
360     set qtyid [canvas-horiz-stack stackx 0 $y $bind \
361                    text -anchor nw -font fixed -text $qty]
362
363     if {!$inport} {
364         canvas-horiz-stack stackx 0 $imy $bind \
365             image -anchor nw -image icon/atsea
366         incr stackx
367     }
368     
369     upvar #0 vc_code2abbrev($class) vcabb
370     if {![info exists vcabb]} {
371         set vcabb vc-$class
372         image create bitmap icon/$vcabb -data \
373             [exec pbmtext -builtin fixed $class | pnminvert | pnmcrop >t.pnm]
374     }
375     canvas-horiz-stack stackx -1 $imy $bind \
376             image -anchor nw -image icon/$vcabb
377
378     if {[string length $subclass]} {
379         canvas-horiz-stack stackx 0 $y $bind \
380             text -anchor nw -font fixed -text \
381             $subclass
382     }
383
384     incr stackx
385     set lockownicon [code-lockown2icon $lockown]
386     if {[string length $lockownicon]} {
387         canvas-horiz-stack stackx 0 $imy $bind \
388             image -anchor nw -image $lockownicon
389         incr stackx
390     }
391     
392     if {[string length $xabbrev]} {
393         canvas-horiz-stack stackx 0 $y $bind \
394             text -anchor nw -font fixed -text \
395             $xabbrev
396     }
397     
398     set bbox [$canvas bbox $qtyid]
399     set ny [lindex $bbox 3]
400     set bid [$canvas create rectangle \
401                  $x $y $stackx $ny \
402                  -fill white]
403
404     set y $ny
405     $canvas lower $bid $qtyid
406
407     $canvas bind $bid <ButtonPress> $bind
408 }
409
410 proc show-report-decode {code} {
411     global vc_code2full
412
413     manyset [split $code _] inport classcode subclass lockown xabbrev
414     manyset [split $lockown ""] lock notown
415     
416     report-set inport [lindex {{At Sea} {In port}} $inport]
417     report-set class $vc_code2full($classcode)
418
419     global smash_subclass
420     if {$smash_subclass >= 2} {
421         report-set subclass "(Any subclass)"
422     } elseif {[
423                upvar #0 vsc_code2report($subclass) subclass_report
424                info exists subclass_report
425               ]} {
426         report-set subclass $subclass_report
427     } else {
428         report-set subclass "Subclass \"$subclass\""
429     }
430
431     report-set lock [lindex {
432         {Battle ready} {Unlocked} {Locked}
433         {(All lock states)} {(Not battle ready)}
434     } $lock]
435
436     switch -exact $notown {
437         0 { report-set own "Yours" }
438         1 { report-set own "Other pirate's" }
439         2 { report-set own "Owner unknown" }
440         3 { report-set own "(All ownerships)" }
441         4 - 5 { report-set own "(Yours/unknown)" }
442         default { report-set own "?? $notown" }
443     }
444
445     if {[string length $xabbrev]} {
446         report-set xabbrev "Notes flags: $xabbrev"
447     } else {
448         report-set xabbrev "No flags in notes"
449     }
450 }
451
452 #---------- common to smashing and filtering ----------
453
454 proc make-control {parent ctrl label ekind} {
455     debug "MAKE-CONTROL [list $parent $ctrl $label $ekind]"
456     label $parent.lab_$ctrl -text $label -justify left
457     $ekind $parent.$ctrl
458     manyset [grid size $parent] dummy row
459     incr row
460     grid configure $parent.lab_$ctrl -row $row -column 0 -sticky nw -pady 4
461     grid configure $parent.$ctrl -row $row -column 1 -sticky w -pady 3
462     return $parent.$ctrl
463 }
464
465 proc begin-control-grid {cw count rows inrow} {
466     if {!$inrow} { set inrow [expr {($count + $rows) / $rows}] }
467     upvar #0 control_grid_properties($cw) props
468     set props [list $rows $inrow]
469     return $cw
470 }
471
472 proc make-control-grid-entry {cw kind ix ekind args} {
473     upvar #0 control_grid_properties($cw) props
474     manyset $props rows inrow
475
476     set ew $cw.$ix
477     eval [list $ekind $ew] $args
478
479     switch -exact $kind {
480         ix {
481             grid configure $ew -sticky sw \
482                 -row [expr {$ix / $inrow}] \
483                 -column [expr {$ix % $inrow}]
484         }
485         final {
486             grid configure $ew -sticky se \
487                 -row [expr {$rows-1}] \
488                 -column [expr {$inrow-1}]
489         }
490         default {
491             error "$kind ?"
492         }
493     }
494     return $ew
495 }
496
497 #---------- smashing ----------
498
499 set smash_subclass 0
500 set smash_owner 0
501
502 proc smash-code {code} {
503     manyset [split $code _] inport class subclass lockown xabbrev
504
505     global smash_subclass
506     if {$smash_subclass > 1} {
507         set subclass {}
508     } elseif {$smash_subclass && [string length $subclass]} {
509         set subclass !
510     }
511
512     global smash_owner
513     switch $smash_owner {
514         0 { }
515         1 { regsub {[12]$} $lockown 5 lockown }
516         2 {
517             if {[regexp {^0.} $lockown]} {
518                 # battle ready / all lock states
519                 set lockown 03
520             } elseif {[regexp {^.0} $lockown]} {
521                 # not battle ready / yours
522                 set lockown 40
523             } else {
524                 # state (not battle ready) / not known to be yours
525                 regsub {.$} $lockown 4 lockown
526             }
527         }
528         3 { regsub {.$} $lockown {3} lockown }
529         4 { set lockown 33 }
530     }
531
532     return [join [list $inport $class $subclass $lockown $xabbrev] _]
533 }
534
535 proc make-smasher {sma label ekind} {
536     return [make-control .smash $sma $label $ekind]
537 }
538
539 proc make-radio-smasher {sma label variable descs rows inrow} {
540     set w [make-smasher $sma $label frame]
541     begin-control-grid $w [llength $descs] $rows $inrow
542     for {set i 0} {$i < [llength $descs]} {incr i} {
543         make-control-grid-entry $w ix $i \
544             radiobutton \
545             -variable $variable -value $i -command redraw-needed \
546             -text [lindex $descs $i]
547     }
548 }
549
550 #---------- filtering ----------
551
552 set filters {}
553
554 proc filter-values/size {} { global vc_codes; return $vc_codes }
555 proc filter-icon/size {code} {
556     upvar #0 vc_code2abbrev($code) abb
557     return icon/$abb
558 }
559 proc filter-default/size {code} { return 1 }
560 proc filter-says-yes/size {codel} {
561     set sizecode [lindex $codel 1]
562     upvar #0 filter_size($sizecode) yes
563     return $yes
564 }
565
566 proc filter-values/lockown {} {
567     foreach lv {0 1 2} {
568         foreach ov {0 1 2} {
569             lappend vals "$lv$ov"
570         }
571     }
572     return $vals
573 }
574 proc filter-icon/lockown {lockown} { return [code-lockown2icon $lockown] }
575 proc filter-default/lockown {lockown} {
576     return [regexp {^[01]|^2[^1]} $lockown]
577 }
578 proc filter-says-yes/lockown {codel} {
579     set lockown [lindex $codel 3]
580     upvar #0 filter_lockown($lockown) yes
581     debug "FILTER-SAYS-YES/LOCKOWN $codel $lockown $yes"
582     return $yes
583 }
584
585 proc filter-validate/xabbre {re} {
586     if {[catch {
587         regexp -- $re {}
588     } emsg]} {
589         regsub {^.*:\s*} $emsg {} emsg
590         regsub {^.*(.{30})$} $emsg {\1} emsg
591         return $emsg
592     }
593     return {}
594 }
595 proc filter-says-yes/xabbre {codel} {
596     global filter_xabbre
597     set xabbrev [lindex $codel 4]
598     return [regexp -- $filter_xabbre $xabbrev]
599 }
600
601 proc filter-tickbox-flip {fil} {
602     upvar #0 filter_$fil vars
603     set values [filter-values/$fil]
604     foreach val $values {
605         set vars($val) [expr {!$vars($val)}]
606     }
607     redraw-needed
608 }
609
610 proc make-tickbox-filter {fil label rows inrow} {
611     upvar #0 filter_$fil vars
612     set values [filter-values/$fil]
613     set count [llength $values]
614     set noicons [catch { info args filter-icon/$fil }]
615
616     set fw [make-filter $fil $label frame]
617     begin-control-grid $fw $count $rows $inrow
618
619     for {set ix 0} {$ix < $count} {incr ix} {
620         set val [lindex $values $ix]
621         set vars($val) [filter-default/$fil $val]
622         set ew [make-control-grid-entry $fw ix $ix checkbutton \
623                     -variable filter_${fil}($val) \
624                     -font fixed \
625                     -command [list redraw-needed tickbox-filter $fil $val]]
626         if {!$noicons} {
627             $fw.$ix configure -image [filter-icon/$fil $val] -height 16
628         } else {
629             $fw.$ix configure -text [filter-map/$fil $val]
630         }
631     }
632     [make-control-grid-entry $fw final invert button] \
633         configure \
634         -text flip -command [list filter-tickbox-flip $fil] \
635         -padx 0 -pady 0
636 }
637
638 proc entry-filter-changed {fw fil n1 n2 op} {
639     global errorInfo
640     upvar #0 filter_$fil realvar
641     upvar #0 filterentered_$fil entryvar
642     global def_background
643     debug "entry-filter-changed $fw $fil $entryvar"
644     if {[catch {
645         set error [filter-validate/$fil $entryvar]
646         if {[string length $error]} {
647             $fw.error configure -text $error -foreground white -background red
648         } else {
649             $fw.error configure -text { } -background $def_background
650             set realvar $entryvar
651             redraw-needed
652         }
653     } emsg]} {
654         puts stderr "FILTER CHECK ERROR $emsg $errorInfo"
655     }
656 }
657
658 proc make-entry-filter {fil label def} {
659     global filterentered_$fil
660     upvar #0 filter_$fil realvar
661     set realvar $def
662     set fw [make-filter $fil $label frame]
663     entry $fw.entry -textvariable filterentered_$fil
664     label $fw.error
665     glset def_background [$fw.error cget -background]
666     trace add variable filterentered_$fil write \
667         [list entry-filter-changed $fw $fil]
668     pack $fw.entry $fw.error -side top -anchor w
669 }
670
671 proc make-filter {fil label ekind} {
672     global filters
673     lappend filters $fil
674     return [make-control .filter $fil $label $ekind]
675 }
676
677 proc make-filters {} {
678     make-tickbox-filter size Size 2 0
679     make-tickbox-filter lockown "Lock/\nowner" 2 6
680     make-entry-filter xabbre "Flags\n regexp" {}
681 }
682
683 proc filterstyle-changed {n1 n2 op} {
684     global filterstyle
685     debug "filterstyle-changed $filterstyle"
686     redraw-needed
687 }
688
689 proc filters-say-yes {code} {
690     global filters filterstyle
691     set codel [split $code _]
692     set lockown [lindex $codel 3]
693     switch -exact $filterstyle {
694         0 { return 1 }
695         1 { return [filter-default/lockown $lockown] }
696         2 { return [regexp {^.0} $lockown] }
697         3 { }
698         default { error $filterstyle }
699     }
700     
701     foreach fil $filters {
702         if {![filter-says-yes/$fil $codel]} {
703             debug "FILTERS-SAY-YES $code NO $fil"
704             return 0
705         }
706     }
707     debug "FILTERS-SAY-YES $code YES $filters"
708     return 1
709 }
710     
711 #---------- loading and parsing the clipboard (vessel locations) ----------
712
713 proc vessel {vin} {
714     global pirate notes_used note_missings newnotes
715     upvar 1 $vin vi
716
717     set codel {}
718     lappend codel [errexpect-arrayget-boolean vi inPort]
719
720     set gameclass [errexpect-arrayget vi vesselClass]
721     upvar #0 vc_game2code($gameclass) class
722     if {![info exists class]} {
723         set class "($gameclass)"
724         upvar #0 vc_code2abbrev($class) vcabb
725         set vcabb vc-$class
726         set data [exec pbmtext -builtin fixed " $gameclass " \
727                  | pnminvert | pnmcrop | pbmtoxbm]
728         debug "INVENTED ICON $vcabb $data"
729         image create bitmap icon/$vcabb -data $data
730             
731         global vc_code2full
732         set vc_code2full($class) "Type \"$gameclass\""
733     }
734     lappend codel $class
735
736     set gamesubclass [errexpect-arrayget vi vesselSubclass]
737     upvar #0 vsc_game2code($gamesubclass) subclass
738     if {[info exists subclass]} {
739         lappend codel $subclass
740     } else {
741         lappend codel ($gamesubclass)
742     }
743
744     switch -exact [errexpect-arrayget vi isLocked]/[ \
745                    errexpect-arrayget vi isBattleReady] {
746         true/false      { set lock 2 }
747         false/false     { set lock 1 }
748         false/true      { set lock 0 }
749         default         { errexpect-error "unexpected isLocked/isBattleReady" }
750     }
751
752     set vid [errexpect-arrayget vi vesselId]
753     upvar #0 notes($vid) note
754     set realname [errexpect-arrayget vi vesselName]
755     set island [errexpect-arrayget vi islandName]
756
757     set owner {}
758     set xabbrev {}
759     if {[info exists note]} {
760         manyset $note lno notename owner xabbrev
761         if {[string compare -nocase $realname $notename]} {
762             note-info $lno $vid $realname $island \
763                 "notes say name is $notename"
764         }
765         if {[string length $owner]} {
766             if {![string compare $owner $pirate]} {
767                 set notown 0
768             } else {
769                 set notown 1
770             }
771         } else {
772             set notown 2
773         }
774         append abbrev $xabbrev
775         set notes_used($vid) 1
776
777     } else {
778         set notown 2
779         lappend note_missings [list $island $realname $vid]
780     }
781
782     lappend codel "$lock$notown" $xabbrev
783     lappend newnotes [list $vid $realname $owner $xabbrev]
784     set kk "$island [join $codel _]"
785     upvar #0 found($kk) k
786     lappend k [list $vid $realname $owner]
787  
788     debug "CODED $kk $vid $realname"
789 }
790
791 set clipboard {}
792 proc parse-clipboard {} {
793     global clipboard found notes notes_used newnotes
794
795     catch { unset found }
796     catch { unset notes_used }
797     glset note_infos {}
798     glset note_missings {}
799
800     set newnotes {}
801     
802     set itemre { (\w+) = ([^=]*) }
803     set manyitemre "^\\\[ $itemre ( (?: ,\\ $itemre)* ) \\]\$"
804     debug $manyitemre
805
806     set lno 0
807     foreach l [split $clipboard "\n"] {
808         incr lno
809         errexpect-setline $lno $l
810         if {![string length $l]} continue
811         catch { unset vi }
812         while 1 {
813                 if {![regexp -expanded $manyitemre $l dummy \
814                         thiskey thisval rhs]} {
815                     errexpect-error "badly formatted"
816                 }
817                 set vi($thiskey) $thisval
818                 if {![string length $rhs]} break
819                 regsub {^, } $rhs {} rhs
820                 set l "\[$rhs\]"
821         }
822         vessel vi
823     }
824
825     if {[llength $newnotes]} {
826         foreach vid [lsort [array names notes]] {
827             if {![info exists notes_used($vid)]} {
828                 manyset $notes($vid) lno notename
829                 note-info $lno $vid $notename {} \
830                     "vessel in notes no longer found"
831             }
832         }
833     }
834 }
835
836 proc load-clipboard-file {fn} {
837     set f [open $fn]
838     glset clipboard [read $f]
839     close $f
840 }
841
842
843 #---------- loading and parsing the chart ----------
844
845 proc load-chart {} {
846     global chart scraper
847     debug "FETCHING CHART"
848     set chart [eval exec $scraper [list | perl -we {
849         use strict;
850         use CommodsScrape;
851         use IO::File;
852         use IO::Handle;
853         yppedia_chart_parse(\*STDIN, (new IO::File ">/dev/null"),
854                 sub { sprintf "%d %d", @_; },
855                 sub { printf "archlabel %d %d %s\n", @_; },
856                 sub { printf "island %s {%s} %s\n", @_; },
857                 sub { printf "league %s %s %s.\n", @_; },
858                 sub { printf STDERR "warning: %s: incomprehensible: %s", @_; }
859                         );
860         STDOUT->error and die $!;
861     }]]
862 }
863
864
865 set scale 16
866
867 proc coord {c} {
868         global scale
869         return [expr {$c * $scale}]
870 }
871
872 proc chart-got/archlabel {args} { }
873 proc chart-got/island {x y isle sizecol} {
874         debug "ISLE $x $y $isle $sizecol"
875         global canvas isleloc
876         set isleloc($isle) [list $x $y]
877         set sz 5
878 #       $canvas create oval \
879 #               [expr {[coord $x] - $sz}] [expr {[coord $y] - $sz}] \
880 #               [expr {[coord $x] + $sz}] [expr {[coord $y] + $sz}] \
881 #               -fill blue
882         set colour "#888"
883         if {[string match *_col $sizecol]} { set colour black }
884         $canvas create text [coord $x] [coord $y] \
885                 -text $isle -anchor s -fill $colour
886 }
887 proc chart-got/league {x1 y1 x2 y2 kind} {
888 #       debug "LEAGUE $x1 $y1 $x2 $y2 $kind"
889         global canvas
890         set l [$canvas create line \
891                 [coord $x1] [coord $y1] \
892                 [coord $x2] [coord $y2]]
893         if {![string compare $kind .]} {
894                 $canvas itemconfigure $l -dash .
895         }
896 }
897
898 proc debug-filter-array {array} {
899     upvar #0 $array a
900     set m " FILTER $array"
901     foreach k [lsort [array names a]] {
902         append m " $k=$a($k)"
903     }
904     debug $m
905 }
906
907 proc redraw-needed {args} {
908     global redraw_after
909     debug "REDRAW NEEDED $args"
910     if {[info exists redraw_after]} return
911
912     global filterstyle
913     debug " FILTER style $filterstyle"
914     debug-filter-array filter_size
915     debug-filter-array filter_lockown
916     global filter_xabbre
917     debug " FILTER xabbre $filter_xabbre"
918
919     set redraw_after [after 250 draw]
920 }
921
922 proc draw {} {
923     global chart found isleloc canvas redraw_after islandnames smfound
924
925     catch { after cancel $redraw_after }
926     catch { unset redraw_after }
927     
928     $canvas delete all
929
930     foreach l [split $chart "\n"] {
931 #       debug "CHART-GOT $l"
932         set proc [lindex $l 0]
933         eval chart-got/$proc [lrange $l 1 end]
934     }
935
936     catch { unset smfound }
937     foreach key [lsort [array names found]] {
938         regexp {^(.*) (\S+)$} $key dummy islandname code
939
940         if {![filters-say-yes $code]} continue
941
942         set smcode [smash-code $code]
943         debug "smashed $code => $smcode"
944         set smkey "$islandname $smcode"
945         foreach vessel $found($key) { lappend smfound($smkey) $vessel }
946     }
947
948     set islandnames {}
949     set lastislandname {}
950     foreach smkey [lsort [array names smfound]] {
951         set c [llength $smfound($smkey)]
952         regexp {^(.*) (\S+)$} $smkey dummy islandname code
953         debug "SHOWING [list $smkey $c $islandname $code l=$lastislandname]"
954
955         if {[string compare $lastislandname $islandname]} {
956                 manyset $isleloc($islandname) x y
957                 set x [coord $x]
958                 set y [coord $y]
959                 set lastislandname $islandname
960                 lappend islandnames $islandname
961 #               debug "START Y $y"
962         }
963
964         if {$c > 1} { set qty [format %d $c] } else { set qty {} }
965         code2canvas $code $canvas $x y $qty 2 \
966             [list show-report $islandname $code]
967 #       debug "NEW Y $y"
968     }
969
970     panner::updatecanvas-bbox .cp.ctrl.pan
971
972     islandnames-update
973 }
974
975
976 #---------- parser error reporting ----------
977
978 proc parser-control-create {w base invokebuttontext etl_title} {
979     frame $w
980     button $w.do -text $invokebuttontext -command invoke_$base -pady 3
981
982     frame $w.resframe -width 120 -height 32
983     button $w.resframe.res -text {} -anchor nw \
984         -padx 1 -pady 1 -borderwidth 0 -justify left
985     glset deffont_$base [$w.resframe.res cget -font]
986     place $w.resframe.res -relx 0.5 -y 0 -anchor n
987
988     pack $w.do -side top
989     pack $w.resframe -side top -expand y -fill both
990
991     set eb .err_$base
992     toplevel $eb
993     wm withdraw $eb
994     wm title $eb "where-vessels - $etl_title"
995     wm protocol $eb WM_DELETE_WINDOW [list wm withdraw $eb]
996
997     label $eb.title -text $etl_title
998     pack $eb.title -side top
999
1000     button $eb.close -text Close -command [list wm withdraw $eb]
1001     pack $eb.close -side bottom
1002
1003     frame $eb.emsg -bd 2 -relief groove
1004     label $eb.emsg.lab -anchor nw -text "Error:"
1005     text $eb.emsg.text -height 1
1006     pack $eb.emsg.text -side bottom -fill x
1007     pack $eb.emsg.lab -side left
1008
1009     pack $eb.emsg -side top -pady 2 -fill x
1010
1011     frame $eb.text -bd 2 -relief groove
1012     pack $eb.text -side bottom -pady 2 -fill both -expand y
1013     
1014     label $eb.text.lab -anchor nw
1015
1016     text $eb.text.text -width 85 \
1017         -xscrollcommand [list $eb.text.xscroll set] \
1018         -yscrollcommand [list $eb.text.yscroll set]
1019     $eb.text.text tag configure error \
1020         -background red -foreground white
1021
1022     scrollbar $eb.text.xscroll -orient horizontal \
1023         -command [list $eb.text.text xview]
1024     scrollbar $eb.text.yscroll -orient vertical \
1025         -command [list $eb.text.text yview]
1026
1027     grid configure $eb.text.lab -row 0 -column 0 -sticky w -columnspan 2
1028     grid configure $eb.text.text -row 1 -column 0 -sticky news
1029     grid configure $eb.text.yscroll -sticky ns -row 1 -column 1
1030     grid configure $eb.text.xscroll -sticky ew -row 2 -column 0
1031     grid rowconfigure $eb.text 0 -weight 0
1032     grid rowconfigure $eb.text 1 -weight 1
1033     grid rowconfigure $eb.text 2 -weight 0
1034     grid columnconfigure $eb.text 0 -weight 1
1035     grid columnconfigure $eb.text 1 -weight 0
1036 }
1037
1038 proc parser-control-ok-core {w base background show} {
1039     debug "parser-control-ok-core $w $base $background $show"
1040     upvar #0 deffont_$base deffont
1041     $w.resframe.res configure \
1042         -background $background -disabledforeground black -font $deffont \
1043         -state disabled -command {} \
1044         -text $show
1045 }    
1046 proc parser-control-ok {w base show} {
1047     parser-control-ok-core $w $base green $show
1048 }
1049 proc parser-control-none {w base show} {
1050     parser-control-ok-core $w $base blue $show
1051 }
1052 proc parser-control-failed-core {w base foreground background smallfont
1053                                  tiny summary fulldesc fulldata} {
1054     debug "parser-control-failed-core $w $base $summary $fulldesc"
1055     upvar #0 deffont_$base deffont
1056     set eb .err_$base
1057
1058     $eb.emsg.text delete 0.0 end
1059     $eb.emsg.text insert end $summary
1060
1061     $eb.text.lab configure -text $fulldesc
1062     $eb.text.text delete 0.0 end
1063     $eb.text.text insert end $fulldata
1064
1065     regsub -all {.{18}} $tiny "&\n" ewrap
1066
1067     if {$smallfont} {
1068         set font fixed
1069     } else {
1070         set font $deffont
1071     }
1072
1073     $w.resframe.res configure \
1074         -background $background -foreground $foreground -font $font \
1075         -state normal -command [list wm deiconify $eb] \
1076         -text $ewrap
1077 }
1078     
1079 proc parser-control-failed-expected {w base emsg lno ei fulldesc newdata} {
1080     set eb .err_$base
1081
1082     set line [lindex [split $ei "\n"] 0]
1083     debug "parser-control-failed-expected: $w $base: $lno: $emsg\n $line"
1084
1085     parser-control-failed-core $w $base \
1086         white red 1 \
1087         "err: [string trim $emsg]: \"$line\"" \
1088         "at line $lno: $emsg" \
1089         $fulldesc $newdata
1090
1091     $eb.text.text tag add error $lno.0 $lno.end
1092     $eb.text.text see $lno.0    
1093 }
1094 proc parser-control-failed-unexpected {w base emsg ei} {
1095     global errorInfo
1096     parser-control-failed-core $w $base \
1097         black yellow 1 \
1098         $emsg $emsg "Details and stack trace:" $ei
1099 }
1100
1101 proc reparse {base varname old fulldesc okshow noneshow parse ok} {
1102     upvar #0 $varname var
1103     manyset [errexpect-catch {
1104         uplevel 1 $parse
1105         if {[string length [string trim $var]]} {
1106             parser-control-ok .cp.ctrl.$base $base $okshow
1107         } else {
1108             parser-control-none .cp.ctrl.$base $base $noneshow
1109         }
1110     }] failed emsg lno ei
1111     if {$failed} {
1112         parser-control-failed-expected .cp.ctrl.$base $base \
1113             $emsg $lno $ei $fulldesc $var
1114         set var $old
1115         uplevel 1 $parse
1116     } else {
1117         uplevel 1 $ok
1118     }
1119 }
1120
1121 #---------- island names selection etc. ----------
1122
1123 proc islandnames-update {} {
1124     global islandnames
1125     .islands.count configure -text [format "ships at %d island(s)" \
1126                                         [llength $islandnames]]
1127 }
1128
1129 proc islandnames-select {} {
1130     .islands.clip configure -relief sunken -state disabled
1131     selection own -command islandnames-deselect .islands.clip
1132 }
1133 proc islandnames-deselect {} {
1134     .islands.clip configure -relief raised -state normal
1135 }
1136
1137 proc islandnames-handler {offset maxchars} {
1138     global islandnames
1139     return [string range [join $islandnames ", "] \
1140                 $offset [expr {$offset+$maxchars-1}]]
1141 }
1142
1143 #---------- main user interface ----------
1144
1145 proc widgets-setup {} {
1146     global canvas debug pirate ocean filterstyle
1147
1148     wm geometry . 1024x600
1149     wm title . "where-vessels - $pirate on the $ocean ocean"
1150
1151     #----- map -----
1152
1153     frame .f -border 1 -relief groove
1154     set canvas .f.c
1155     canvas $canvas
1156     pack $canvas -expand 1 -fill both
1157     pack .f -expand 1 -fill both -side left
1158
1159     #----- control panels and filter -----
1160
1161     frame .cp
1162     frame .smash -relief groove -bd 2 -padx 1
1163     frame .filter -relief groove -bd 2 -padx 1
1164     frame .islands -pady 2
1165     pack .cp .filter .islands .smash -side top
1166
1167     label .smash.title -text Smash
1168     grid .smash.title -row 0 -column 0 -columnspan 2
1169
1170     make-radio-smasher subclass Subclass smash_subclass \
1171         {Show Normal/LE Hide} 1 0
1172
1173     make-radio-smasher owner Owner smash_owner \
1174         {Show Yours? {For you} Lock Hide} 2 3
1175
1176     set filterstyle 1
1177     trace add variable filterstyle write filterstyle-changed
1178
1179     frame .filter.title
1180     label .filter.title.title -text Show
1181     pack .filter.title.title -side left
1182     for {set fing 0} {$fing < 4} {incr fing} {
1183         radiobutton .filter.title.f$fing \
1184             -variable filterstyle -value $fing \
1185             -text [lindex {All Useable Mine These:} $fing]
1186         pack .filter.title.f$fing -side left
1187     }
1188
1189     grid configure .filter.title -row 0 -column 0 -columnspan 2
1190
1191     #----- control panel -----
1192
1193     frame .cp.ctrl
1194     pack .cp.ctrl -side left -anchor n
1195
1196     debug "BBOX [$canvas bbox all]"
1197
1198     panner::canvas-scroll-bbox .f.c
1199     panner::create .cp.ctrl.pan .f.c 120 120 $debug
1200
1201     pack .cp.ctrl.pan -side top -pady 0 -padx 5
1202     frame .cp.ctrl.zoom
1203     pack .cp.ctrl.zoom -side top
1204
1205     button .cp.ctrl.zoom.out -text - -font {Courier 16} -command {zoom /2} -pady 0
1206     button .cp.ctrl.zoom.in  -text + -font {Courier 16} -command {zoom *2} -pady 0
1207     pack .cp.ctrl.zoom.out .cp.ctrl.zoom.in -side left
1208
1209     parser-control-create .cp.ctrl.acquire \
1210         acquire Acquire \
1211         "Clipboard parsing error" \
1212         
1213     pack .cp.ctrl.acquire -side top -pady 2
1214
1215     parser-control-create .cp.ctrl.notes \
1216         notes "Reload notes" \
1217         "Vessel notes loading report" \
1218         
1219     pack .cp.ctrl.notes -side top -pady 2
1220
1221     #----- island name count and copy -----
1222
1223     label .islands.count
1224     button .islands.clip -text "copy island names" -pady 2 -padx 2 \
1225          -command islandnames-select
1226     selection handle .islands.clip islandnames-handler
1227     pack .islands.count .islands.clip -side left
1228
1229     #----- decoding etc. report -----
1230
1231     frame .cp.report
1232     pack .cp.report -side left -anchor n
1233
1234     label .cp.report.island -text { }
1235
1236     canvas .cp.report.abbrev -width 1 -height 15
1237
1238     frame .cp.report.code
1239     label .cp.report.code.lab -text Code:
1240     glset report_code { }
1241     entry .cp.report.code.code -state readonly \
1242         -textvariable report_code -width 15
1243     pack .cp.report.code.lab .cp.report.code.code -side left
1244     frame .cp.report.details -bd 2 -relief groove -padx 2 -pady 2
1245
1246     listbox .cp.report.list -height 5
1247
1248     pack .cp.report.island .cp.report.abbrev .cp.report.details \
1249         .cp.report.list -side top
1250     #pack .cp.report.code -side top
1251     pack configure .cp.report.details -fill x
1252
1253     foreach sw {inport class subclass lock own xabbrev} {
1254         label .cp.report.details.$sw -text { }
1255         pack .cp.report.details.$sw -side top -anchor w
1256     }
1257 }
1258
1259 proc report-set {sw val} { .cp.report.details.$sw configure -text $val }
1260
1261 proc show-report {islandname code} {
1262     .cp.report.island configure -text $islandname
1263
1264     .cp.report.abbrev delete all
1265     set y 2
1266     code2canvas $code .cp.report.abbrev 5 y {} 0 {}
1267     manyset [.cp.report.abbrev bbox all] minx dummy maxx dummy
1268     .cp.report.abbrev configure -width [expr {$maxx-$minx+4}]
1269
1270     glset report_code $code
1271     show-report-decode $code
1272
1273     set kk "$islandname $code"
1274     upvar #0 smfound($kk) k
1275
1276     .cp.report.list delete 0 end
1277
1278     foreach entry $k {
1279         manyset $entry vid name owner
1280         lappend owned($owner) $name
1281     }
1282
1283     foreach owner [lsort [array names owned]] {
1284         if {[string length $owner]} {
1285             set owndesc "$owner's"
1286         } else {
1287             set owndesc "Owner unknown"
1288         }
1289         .cp.report.list insert end "$owndesc:"
1290         foreach name $owned($owner) {
1291             .cp.report.list insert end " $name"
1292         }
1293     }
1294 }
1295
1296 proc zoom {extail} {
1297     global scale canvas
1298     set nscale [expr "\$scale $extail"]
1299     debug "ZOOM $scale $nscale"
1300     if {$nscale < 1 || $nscale > 200} return
1301     set scale $nscale
1302     draw
1303 }
1304
1305 proc invoke_acquire {} {
1306     global clipboard errorInfo
1307     set old $clipboard
1308
1309     if {[catch {
1310         set clipboard [clipboard get]
1311     } emsg]} {
1312         parser-control-failed-unexpected .cp.ctrl.acquire acquire \
1313             $emsg "fetching clipboard:\n\n$errorInfo"
1314         return
1315     }
1316
1317     reparse acquire \
1318         clipboard $old "Clipboard contents:" { acquired ok } { no vessels } {
1319             parse-clipboard
1320         } {
1321             display-note-infos
1322         }
1323     draw
1324 }
1325
1326 proc invoke_notes {} {
1327     global notes_data errorInfo notes_loc
1328     set old $notes_data
1329     
1330     if {[catch {
1331         load-notes
1332     } emsg]} {
1333         parser-control-failed-unexpected .cp.ctrl.notes notes \
1334             $emsg "loading $notes_loc:\n\n$errorInfo"
1335         return
1336     }
1337
1338     reparse notes \
1339         notes_data $old "Vessel notes:" "loaded ok" { no notes } {
1340             parse-notes
1341             parse-clipboard
1342         } {
1343             display-note-infos
1344         }
1345     draw
1346 }
1347
1348 #---------- main program ----------
1349
1350 parseargs
1351 argdefaults
1352 httpclientsetup where-vessels
1353 info-cache-update
1354 vesselclasses-init
1355 load-chart
1356 widgets-setup
1357 make-filters
1358
1359 set notes_data {}
1360 if {[catch { parse-clipboard } emsg]} {
1361     puts stderr "$emsg\n$errorInfo"
1362     exit 1
1363 }
1364 after idle invoke_notes
1365
1366 draw
1367
1368 # rsync -r --exclude=\*~ yarrg/icons/. ijackson@chiark.greenend.org.uk:/home/ftp/users/ijackson/yarrg/vessel-info/.