chiark / gitweb /
midas class
[ypp-sc-tools.db-live.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     foreach {game code full} $subclassinfos {
293         if {![regexp {^[A-Z]$} $code code]} { error "bad code" }
294         set vsc_game2code($game) $code
295         set vsc_code2report($code) $full
296     }
297
298     load-icon atsea
299     foreach a {battle borrow dot} {
300         foreach b {ours dot query} {
301             load-icon-combine $a $b
302         }
303     }
304 }
305
306 proc load-icon {icon} {
307     global info_cache
308     image create bitmap icon/$icon -file $info_cache/$icon.xbm
309 }
310
311 proc load-icon-combine {args} {
312     global info_cache
313     set cmd {}
314     set delim "pnmcat -lr "
315     foreach icon $args {
316         append cmd $delim " <(xbmtopbm $info_cache/$icon.xbm)"
317         set delim " <(pbmmake -white 1 1)"
318     }
319     append cmd " | pbmtoxbm"
320     debug "load-icon-combine $cmd"
321     image create bitmap icon/[join $args +] -data [exec bash -c $cmd]
322 }
323
324 proc code-lockown2icon {lockown} {
325     manyset [split $lockown ""] lock notown
326     return icon/[
327                  lindex {battle borrow dot} $lock
328                 ]+[
329                    lindex {ours dot query} $notown
330                   ]
331 }
332
333 proc canvas-horiz-stack {xvar xoff y bind type args} {
334     upvar 1 $xvar x
335     upvar 1 canvas canvas
336     set id [eval $canvas create $type [expr {$x+$xoff}] $y $args]
337     set bbox [$canvas bbox $id]
338     set x [lindex $bbox 2]
339     $canvas bind $id <ButtonPress> $bind
340     return $id
341 }
342
343 proc code2canvas {code canvas x yvar qty qtylen bind} {
344     global vc_code2abbrev
345     upvar 1 $yvar y
346
347     manyset [split $code _] inport class subclass lockown xabbrev
348
349     set stackx $x
350     incr stackx 2
351     set imy [expr {$y+2}]
352
353     if {!$inport} { incr qtylen -1 }
354     if {$qtylen<=0} { set qtylen {} }
355     set qty [format "%${qtylen}s" $qty]
356
357     set qtyid [canvas-horiz-stack stackx 0 $y $bind \
358                    text -anchor nw -font fixed -text $qty]
359
360     if {!$inport} {
361         canvas-horiz-stack stackx 0 $imy $bind \
362             image -anchor nw -image icon/atsea
363         incr stackx
364     }
365     
366     upvar #0 vc_code2abbrev($class) vcabb
367     if {![info exists vcabb]} {
368         set vcabb vc-$class
369         image create bitmap icon/$vcabb -data \
370             [exec pbmtext -builtin fixed $class | pnminvert | pnmcrop >t.pnm]
371     }
372     canvas-horiz-stack stackx -1 $imy $bind \
373             image -anchor nw -image icon/$vcabb
374
375     if {[string length $subclass]} {
376         canvas-horiz-stack stackx 0 $y $bind \
377             text -anchor nw -font fixed -text \
378             $subclass
379     }
380
381     incr stackx
382     canvas-horiz-stack stackx 0 $imy $bind \
383         image -anchor nw -image [code-lockown2icon $lockown]
384     incr stackx
385     
386     if {[string length $xabbrev]} {
387         canvas-horiz-stack stackx 0 $y $bind \
388             text -anchor nw -font fixed -text \
389             $xabbrev
390     }
391     
392     set bbox [$canvas bbox $qtyid]
393     set ny [lindex $bbox 3]
394     set bid [$canvas create rectangle \
395                  $x $y $stackx $ny \
396                  -fill white]
397
398     set y $ny
399     $canvas lower $bid $qtyid
400
401     $canvas bind $bid <ButtonPress> $bind
402 }
403
404 proc show-report-decode {code} {
405     global vc_code2full
406
407     manyset [split $code _] inport classcode subclass lockown xabbrev
408     manyset [split $lockown ""] lock notown
409     
410     report-set inport [lindex {{At Sea} {In port}} $inport]
411     report-set class $vc_code2full($classcode)
412
413     upvar #0 vsc_code2report($subclass) subclass_report
414     if {[info exists subclass_report]} {
415         report-set subclass $subclass_report
416     } else {
417         report-set subclass "Subclass \"$subclass\""
418     }
419
420     report-set lock [lindex {
421         {Battle ready} {Unlocked} {Locked}
422     } $lock]
423
424     switch -exact $notown {
425         0 { report-set own "Yours" }
426         1 { report-set own "Other pirate's" }
427         2 { report-set own "Owner unknown" }
428         default { report-set own "?? $notown" }
429     }
430
431     if {[string length $xabbrev]} {
432         report-set xabbrev "Notes flags: $xabbrev"
433     } else {
434         report-set xabbrev "No flags in notes"
435     }
436 }
437
438 #---------- filtering ----------
439
440 set filters {}
441
442 proc filter-values/size {} { global vc_codes; return $vc_codes }
443 proc filter-icon/size {code} {
444     upvar #0 vc_code2abbrev($code) abb
445     return icon/$abb
446 }
447 proc filter-default/size {code} { return 1 }
448 proc filter-says-yes/size {codel} {
449     set sizecode [lindex $codel 1]
450     upvar #0 filter_size($sizecode) yes
451     return $yes
452 }
453
454 proc filter-values/lockown {} {
455     foreach lv {0 1 2} {
456         foreach ov {0 1 2} {
457             lappend vals "$lv$ov"
458         }
459     }
460     return $vals
461 }
462 proc filter-icon/lockown {lockown} { return [code-lockown2icon $lockown] }
463 proc filter-default/lockown {lockown} {
464     return [regexp {^[01]|^2[^1]} $lockown]
465 }
466 proc filter-says-yes/lockown {codel} {
467     set lockown [lindex $codel 3]
468     upvar #0 filter_lockown($lockown) yes
469     return $yes
470 }
471
472 proc filter-validate/xabbre {re} {
473     if {[catch {
474         regexp -- $re {}
475     } emsg]} {
476         regsub {^.*:\s*} $emsg {} emsg
477         regsub {^.*(.{30})$} $emsg {\1} emsg
478         return $emsg
479     }
480     return {}
481 }
482 proc filter-says-yes/xabbre {codel} {
483     global filter_xabbre
484     set xabbrev [lindex $codel 4]
485     return [regexp -- $filter_xabbre $xabbrev]
486 }
487
488 proc filter-tickbox-flip {fil} {
489     upvar #0 filter_$fil vars
490     set values [filter-values/$fil]
491     foreach val $values {
492         set vars($val) [expr {!$vars($val)}]
493     }
494     redraw-needed
495 }
496
497 proc make-tickbox-filter {fil label rows inrow} {
498     upvar #0 filter_$fil vars
499     set fw [make-filter tickbox $fil $label frame]
500     set values [filter-values/$fil]
501     set nvalues [llength $values]
502     if {!$inrow} {
503         set inrow [expr {($nvalues + $rows) / $rows}]
504     }
505     set noicons [catch { info args filter-icon/$fil }]
506     for {set ix 0} {$ix < $nvalues} {incr ix} {
507         set val [lindex $values $ix]
508         set vars($val) [filter-default/$fil $val]
509         checkbutton $fw.$ix -variable filter_${fil}($val) \
510             -font fixed -command redraw-needed
511         if {!$noicons} {
512             $fw.$ix configure -image [filter-icon/$fil $val] -height 16
513         } else {
514             $fw.$ix configure -text [filter-map/$fil $val]
515         }
516         grid configure $fw.$ix -sticky sw \
517             -row [expr {$ix / $inrow}] \
518             -column [expr {$ix % $inrow}]
519     }
520     button $fw.invert -text flip -command [list filter-tickbox-flip $fil] \
521         -padx 0 -pady 0
522     grid configure $fw.invert -sticky se \
523         -row [expr {$rows-1}] \
524         -column [expr {$inrow-1}]
525 }
526
527 proc entry-filter-changed {fw fil n1 n2 op} {
528     global errorInfo
529     upvar #0 filter_$fil realvar
530     upvar #0 filterentered_$fil entryvar
531     global def_background
532     debug "entry-filter-changed $fw $fil $entryvar"
533     if {[catch {
534         set error [filter-validate/$fil $entryvar]
535         if {[string length $error]} {
536             $fw.error configure -text $error -foreground white -background red
537         } else {
538             $fw.error configure -text { } -background $def_background
539             set realvar $entryvar
540             redraw-needed
541         }
542     } emsg]} {
543         puts stderr "FILTER CHECK ERROR $emsg $errorInfo"
544     }
545 }
546
547 proc make-entry-filter {fil label def} {
548     global filterentered_$fil
549     upvar #0 filter_$fil realvar
550     set realvar $def
551     set fw [make-filter entry $fil $label frame]
552     entry $fw.entry -textvariable filterentered_$fil
553     label $fw.error
554     glset def_background [$fw.error cget -background]
555     trace add variable filterentered_$fil write \
556         [list entry-filter-changed $fw $fil]
557     pack $fw.entry $fw.error -side top -anchor w
558 }
559
560 proc make-filter {kind fil label ekind} {
561     global filters
562     label .filter.lab_$fil -text $label -justify left
563     $ekind .filter.$fil
564     lappend filters $fil
565     set nfilters [llength $filters]
566     grid configure .filter.lab_$fil -row $nfilters -column 0 -sticky nw -pady 4
567     grid configure .filter.$fil -row $nfilters -column 1 -sticky w -pady 3
568     return .filter.$fil
569 }
570
571 proc make-filters {} {
572     make-tickbox-filter size Size 2 0
573     make-tickbox-filter lockown "Lock/\nowner" 2 6
574     make-entry-filter xabbre "Flags\n regexp" {}
575 }
576
577 proc filterstyle-changed {n1 n2 op} {
578     global filterstyle
579     debug "filterstyle-changed $filterstyle"
580     redraw-needed
581 }
582
583 proc filters-say-yes {code} {
584     global filters filterstyle
585     debug "filters-say-yes $code"
586     set codel [split $code _]
587     set lockown [lindex $codel 3]
588     switch -exact $filterstyle {
589         0 { return 1 }
590         1 { return [filter-default/lockown $lockown] }
591         2 { return [regexp {^.0} $lockown] }
592         3 { }
593         default { error $filterstyle }
594     }
595     
596     foreach fil $filters {
597         if {![filter-says-yes/$fil $codel]} { return 0 }
598     }
599     return 1
600 }
601     
602 #---------- loading and parsing the clipboard (vessel locations) ----------
603
604 proc vessel {vin} {
605     global pirate notes_used note_missings newnotes
606     upvar 1 $vin vi
607
608     set codel {}
609     lappend codel [errexpect-arrayget-boolean vi inPort]
610
611     set gameclass [errexpect-arrayget vi vesselClass]
612     upvar #0 vc_game2code($gameclass) class
613     if {![info exists class]} {
614         set class "($gameclass)"
615         upvar #0 vc_code2abbrev($class) vcabb
616         set vcabb vc-$class
617         set data [exec pbmtext -builtin fixed " $gameclass " \
618                  | pnminvert | pnmcrop | pbmtoxbm]
619         debug "INVENTED ICON $vcabb $data"
620         image create bitmap icon/$vcabb -data $data
621             
622         global vc_code2full
623         set vc_code2full($class) "Type \"$gameclass\""
624     }
625     lappend codel $class
626
627     set gamesubclass [errexpect-arrayget vi vesselSubclass]
628     upvar #0 vsc_game2code($gamesubclass) subclass
629     if {[info exists subclass]} {
630         lappend codel $subclass
631     } else {
632         lappend codel ($gamesubclass)
633     }
634
635     switch -exact [errexpect-arrayget vi isLocked]/[ \
636                    errexpect-arrayget vi isBattleReady] {
637         true/false      { set lock 2 }
638         false/false     { set lock 1 }
639         false/true      { set lock 0 }
640         default         { errexpect-error "unexpected isLocked/isBattleReady" }
641     }
642
643     set vid [errexpect-arrayget vi vesselId]
644     upvar #0 notes($vid) note
645     set realname [errexpect-arrayget vi vesselName]
646     set island [errexpect-arrayget vi islandName]
647
648     set owner {}
649     set xabbrev {}
650     if {[info exists note]} {
651         manyset $note lno notename owner xabbrev
652         if {[string compare -nocase $realname $notename]} {
653             note-info $lno $vid $realname $island \
654                 "notes say name is $notename"
655         }
656         if {[string length $owner]} {
657             if {![string compare $owner $pirate]} {
658                 set notown 0
659             } else {
660                 set notown 1
661             }
662         } else {
663             set notown 2
664         }
665         append abbrev $xabbrev
666         set notes_used($vid) 1
667
668     } else {
669         set notown 2
670         lappend note_missings [list $island $realname $vid]
671     }
672
673     lappend codel "$lock$notown" $xabbrev
674     lappend newnotes [list $vid $realname $owner $xabbrev]
675     set kk "$island [join $codel _]"
676     upvar #0 found($kk) k
677     lappend k [list $vid $realname $owner]
678  
679     debug "CODED $kk $vid $realname"
680 }
681
682 set clipboard {}
683 proc parse-clipboard {} {
684     global clipboard found notes notes_used newnotes
685
686     catch { unset found }
687     catch { unset notes_used }
688     glset note_infos {}
689     glset note_missings {}
690
691     set newnotes {}
692     
693     set itemre { (\w+) = ([^=]*) }
694     set manyitemre "^\\\[ $itemre ( (?: ,\\ $itemre)* ) \\]\$"
695     debug $manyitemre
696
697     set lno 0
698     foreach l [split $clipboard "\n"] {
699         incr lno
700         errexpect-setline $lno $l
701         if {![string length $l]} continue
702         catch { unset vi }
703         while 1 {
704                 if {![regexp -expanded $manyitemre $l dummy \
705                         thiskey thisval rhs]} {
706                     errexpect-error "badly formatted"
707                 }
708                 set vi($thiskey) $thisval
709                 if {![string length $rhs]} break
710                 regsub {^, } $rhs {} rhs
711                 set l "\[$rhs\]"
712         }
713         vessel vi
714     }
715
716     if {[llength $newnotes]} {
717         foreach vid [lsort [array names notes]] {
718             if {![info exists notes_used($vid)]} {
719                 manyset $notes($vid) lno notename
720                 note-info $lno $vid $notename {} \
721                     "vessel in notes no longer found"
722             }
723         }
724     }
725 }
726
727 proc load-clipboard-file {fn} {
728     set f [open $fn]
729     glset clipboard [read $f]
730     close $f
731 }
732
733
734 #---------- loading and parsing the chart ----------
735
736 proc load-chart {} {
737     global chart scraper
738     debug "FETCHING CHART"
739     set chart [eval exec $scraper [list | perl -we {
740         use strict;
741         use CommodsScrape;
742         use IO::File;
743         use IO::Handle;
744         yppedia_chart_parse(\*STDIN, (new IO::File ">/dev/null"),
745                 sub { sprintf "%d %d", @_; },
746                 sub { printf "archlabel %d %d %s\n", @_; },
747                 sub { printf "island %s {%s} %s\n", @_; },
748                 sub { printf "league %s %s %s.\n", @_; },
749                 sub { printf STDERR "warning: %s: incomprehensible: %s", @_; }
750                         );
751         STDOUT->error and die $!;
752     }]]
753 }
754
755
756 set scale 16
757
758 proc coord {c} {
759         global scale
760         return [expr {$c * $scale}]
761 }
762
763 proc chart-got/archlabel {args} { }
764 proc chart-got/island {x y isle sizecol} {
765         debug "ISLE $x $y $isle $sizecol"
766         global canvas isleloc
767         set isleloc($isle) [list $x $y]
768         set sz 5
769 #       $canvas create oval \
770 #               [expr {[coord $x] - $sz}] [expr {[coord $y] - $sz}] \
771 #               [expr {[coord $x] + $sz}] [expr {[coord $y] + $sz}] \
772 #               -fill blue
773         set colour "#888"
774         if {[string match *_col $sizecol]} { set colour black }
775         $canvas create text [coord $x] [coord $y] \
776                 -text $isle -anchor s -fill $colour
777 }
778 proc chart-got/league {x1 y1 x2 y2 kind} {
779 #       debug "LEAGUE $x1 $y1 $x2 $y2 $kind"
780         global canvas
781         set l [$canvas create line \
782                 [coord $x1] [coord $y1] \
783                 [coord $x2] [coord $y2]]
784         if {![string compare $kind .]} {
785                 $canvas itemconfigure $l -dash .
786         }
787 }
788
789 proc redraw-needed {} {
790     global redraw_after
791     debug "REDRAW NEEDED"
792     if {[info exists redraw_after]} return
793     set redraw_after [after 250 draw]
794 }
795
796 proc draw {} {
797     global chart found isleloc canvas redraw_after islandnames
798
799     catch { after cancel $redraw_after }
800     catch { unset redraw_after }
801     
802     $canvas delete all
803
804     foreach l [split $chart "\n"] {
805 #       debug "CHART-GOT $l"
806         set proc [lindex $l 0]
807         eval chart-got/$proc [lrange $l 1 end]
808     }
809
810     set islandnames {}
811     set lastislandname {}
812     foreach key [lsort [array names found]] {
813         set c [llength $found($key)]
814 #       debug "SHOWING $key $c"
815         regexp {^(.*) (\S+)$} $key dummy islandname code
816
817         if {![filters-say-yes $code]} continue
818
819         if {[string compare $lastislandname $islandname]} {
820                 manyset $isleloc($islandname) x y
821                 set x [coord $x]
822                 set y [coord $y]
823                 set lastislandname $islandname
824                 lappend islandnames $islandname
825 #               debug "START Y $y"
826         }
827
828         if {$c > 1} { set qty [format %d $c] } else { set qty {} }
829         code2canvas $code $canvas $x y $qty 2 \
830             [list show-report $islandname $code]
831 #       debug "NEW Y $y"
832     }
833
834     panner::updatecanvas-bbox .cp.ctrl.pan
835
836     islandnames-update
837 }
838
839
840 #---------- parser error reporting ----------
841
842 proc parser-control-create {w base invokebuttontext etl_title} {
843     frame $w
844     button $w.do -text $invokebuttontext -command invoke_$base -pady 3
845
846     frame $w.resframe -width 120 -height 32
847     button $w.resframe.res -text {} -anchor nw \
848         -padx 1 -pady 1 -borderwidth 0 -justify left
849     glset deffont_$base [$w.resframe.res cget -font]
850     place $w.resframe.res -relx 0.5 -y 0 -anchor n
851
852     pack $w.do -side top
853     pack $w.resframe -side top -expand y -fill both
854
855     set eb .err_$base
856     toplevel $eb
857     wm withdraw $eb
858     wm title $eb "where-vessels - $etl_title"
859     wm protocol $eb WM_DELETE_WINDOW [list wm withdraw $eb]
860
861     label $eb.title -text $etl_title
862     pack $eb.title -side top
863
864     button $eb.close -text Close -command [list wm withdraw $eb]
865     pack $eb.close -side bottom
866
867     frame $eb.emsg -bd 2 -relief groove
868     label $eb.emsg.lab -anchor nw -text "Error:"
869     text $eb.emsg.text -height 1
870     pack $eb.emsg.text -side bottom -fill x
871     pack $eb.emsg.lab -side left
872
873     pack $eb.emsg -side top -pady 2 -fill x
874
875     frame $eb.text -bd 2 -relief groove
876     pack $eb.text -side bottom -pady 2 -fill both -expand y
877     
878     label $eb.text.lab -anchor nw
879
880     text $eb.text.text -width 85 \
881         -xscrollcommand [list $eb.text.xscroll set] \
882         -yscrollcommand [list $eb.text.yscroll set]
883     $eb.text.text tag configure error \
884         -background red -foreground white
885
886     scrollbar $eb.text.xscroll -orient horizontal \
887         -command [list $eb.text.text xview]
888     scrollbar $eb.text.yscroll -orient vertical \
889         -command [list $eb.text.text yview]
890
891     grid configure $eb.text.lab -row 0 -column 0 -sticky w -columnspan 2
892     grid configure $eb.text.text -row 1 -column 0 -sticky news
893     grid configure $eb.text.yscroll -sticky ns -row 1 -column 1
894     grid configure $eb.text.xscroll -sticky ew -row 2 -column 0
895     grid rowconfigure $eb.text 0 -weight 0
896     grid rowconfigure $eb.text 1 -weight 1
897     grid rowconfigure $eb.text 2 -weight 0
898     grid columnconfigure $eb.text 0 -weight 1
899     grid columnconfigure $eb.text 1 -weight 0
900 }
901
902 proc parser-control-ok-core {w base background show} {
903     debug "parser-control-ok-core $w $base $background $show"
904     upvar #0 deffont_$base deffont
905     $w.resframe.res configure \
906         -background $background -disabledforeground black -font $deffont \
907         -state disabled -command {} \
908         -text $show
909 }    
910 proc parser-control-ok {w base show} {
911     parser-control-ok-core $w $base green $show
912 }
913 proc parser-control-none {w base show} {
914     parser-control-ok-core $w $base blue $show
915 }
916 proc parser-control-failed-core {w base foreground background smallfont
917                                  tiny summary fulldesc fulldata} {
918     debug "parser-control-failed-core $w $base $summary $fulldesc"
919     upvar #0 deffont_$base deffont
920     set eb .err_$base
921
922     $eb.emsg.text delete 0.0 end
923     $eb.emsg.text insert end $summary
924
925     $eb.text.lab configure -text $fulldesc
926     $eb.text.text delete 0.0 end
927     $eb.text.text insert end $fulldata
928
929     regsub -all {.{18}} $tiny "&\n" ewrap
930
931     if {$smallfont} {
932         set font fixed
933     } else {
934         set font $deffont
935     }
936
937     $w.resframe.res configure \
938         -background $background -foreground $foreground -font $font \
939         -state normal -command [list wm deiconify $eb] \
940         -text $ewrap
941 }
942     
943 proc parser-control-failed-expected {w base emsg lno ei fulldesc newdata} {
944     set eb .err_$base
945
946     set line [lindex [split $ei "\n"] 0]
947     debug "parser-control-failed-expected: $w $base: $lno: $emsg\n $line"
948
949     parser-control-failed-core $w $base \
950         white red 1 \
951         "err: [string trim $emsg]: \"$line\"" \
952         "at line $lno: $emsg" \
953         $fulldesc $newdata
954
955     $eb.text.text tag add error $lno.0 $lno.end
956     $eb.text.text see $lno.0    
957 }
958 proc parser-control-failed-unexpected {w base emsg ei} {
959     global errorInfo
960     parser-control-failed-core $w $base \
961         black yellow 1 \
962         $emsg $emsg "Details and stack trace:" $ei
963 }
964
965 proc reparse {base varname old fulldesc okshow noneshow parse ok} {
966     upvar #0 $varname var
967     manyset [errexpect-catch {
968         uplevel 1 $parse
969         if {[string length [string trim $var]]} {
970             parser-control-ok .cp.ctrl.$base $base $okshow
971         } else {
972             parser-control-none .cp.ctrl.$base $base $noneshow
973         }
974     }] failed emsg lno ei
975     if {$failed} {
976         parser-control-failed-expected .cp.ctrl.$base $base \
977             $emsg $lno $ei $fulldesc $var
978         set var $old
979         uplevel 1 $parse
980     } else {
981         uplevel 1 $ok
982     }
983 }
984
985 #---------- island names selection etc. ----------
986
987 proc islandnames-update {} {
988     global islandnames
989     .islands.count configure -text [format "ships at %d island(s)" \
990                                         [llength $islandnames]]
991 }
992
993 proc islandnames-select {} {
994     .islands.clip configure -relief sunken -state disabled
995     selection own -command islandnames-deselect .islands.clip
996 }
997 proc islandnames-deselect {} {
998     .islands.clip configure -relief raised -state normal
999 }
1000
1001 proc islandnames-handler {offset maxchars} {
1002     global islandnames
1003     return [string range [join $islandnames ", "] \
1004                 $offset [expr {$offset+$maxchars-1}]]
1005 }
1006
1007 #---------- main user interface ----------
1008
1009 proc widgets-setup {} {
1010     global canvas debug pirate ocean filterstyle
1011
1012     wm geometry . 1024x600
1013     wm title . "where-vessels - $pirate on the $ocean ocean"
1014
1015     #----- map -----
1016
1017     frame .f -border 1 -relief groove
1018     set canvas .f.c
1019     canvas $canvas
1020     pack $canvas -expand 1 -fill both
1021     pack .f -expand 1 -fill both -side left
1022
1023     #----- control panels and filter -----
1024
1025     frame .cp
1026     frame .filter -relief groove -bd 2 -padx 1
1027     frame .islands -pady 2
1028     pack .cp .filter .islands -side top
1029
1030     set filterstyle 1
1031     trace add variable filterstyle write filterstyle-changed
1032
1033     frame .filter.title
1034     label .filter.title.title -text Show
1035     pack .filter.title.title -side left
1036     for {set fing 0} {$fing < 4} {incr fing} {
1037         radiobutton .filter.title.f$fing \
1038             -variable filterstyle -value $fing \
1039             -text [lindex {All Useable Mine These:} $fing]
1040         pack .filter.title.f$fing -side left
1041     }
1042
1043     grid configure .filter.title -row 0 -column 0 -columnspan 2
1044
1045     #----- control panel -----
1046
1047     frame .cp.ctrl
1048     pack .cp.ctrl -side left -anchor n
1049
1050     debug "BBOX [$canvas bbox all]"
1051
1052     panner::canvas-scroll-bbox .f.c
1053     panner::create .cp.ctrl.pan .f.c 120 120 $debug
1054
1055     pack .cp.ctrl.pan -side top -pady 0 -padx 5
1056     frame .cp.ctrl.zoom
1057     pack .cp.ctrl.zoom -side top
1058
1059     button .cp.ctrl.zoom.out -text - -font {Courier 16} -command {zoom /2} -pady 0
1060     button .cp.ctrl.zoom.in  -text + -font {Courier 16} -command {zoom *2} -pady 0
1061     pack .cp.ctrl.zoom.out .cp.ctrl.zoom.in -side left
1062
1063     parser-control-create .cp.ctrl.acquire \
1064         acquire Acquire \
1065         "Clipboard parsing error" \
1066         
1067     pack .cp.ctrl.acquire -side top -pady 2
1068
1069     parser-control-create .cp.ctrl.notes \
1070         notes "Reload notes" \
1071         "Vessel notes loading report" \
1072         
1073     pack .cp.ctrl.notes -side top -pady 2
1074
1075     #----- island name count and copy -----
1076
1077     label .islands.count
1078     button .islands.clip -text "copy island names" -pady 2 -padx 2 \
1079          -command islandnames-select
1080     selection handle .islands.clip islandnames-handler
1081     pack .islands.count .islands.clip -side left
1082
1083     #----- decoding etc. report -----
1084
1085     frame .cp.report
1086     pack .cp.report -side left -anchor n
1087
1088     label .cp.report.island -text { }
1089
1090     canvas .cp.report.abbrev -width 1 -height 15
1091
1092     frame .cp.report.code
1093     label .cp.report.code.lab -text Code:
1094     glset report_code { }
1095     entry .cp.report.code.code -state readonly \
1096         -textvariable report_code -width 15
1097     pack .cp.report.code.lab .cp.report.code.code -side left
1098     frame .cp.report.details -bd 2 -relief groove -padx 2 -pady 2
1099
1100     listbox .cp.report.list -height 5
1101
1102     pack .cp.report.island .cp.report.abbrev .cp.report.details \
1103         .cp.report.list -side top
1104     #pack .cp.report.code -side top
1105     pack configure .cp.report.details -fill x
1106
1107     foreach sw {inport class subclass lock own xabbrev} {
1108         label .cp.report.details.$sw -text { }
1109         pack .cp.report.details.$sw -side top -anchor w
1110     }
1111 }
1112
1113 proc report-set {sw val} { .cp.report.details.$sw configure -text $val }
1114
1115 proc show-report {islandname code} {
1116     .cp.report.island configure -text $islandname
1117
1118     .cp.report.abbrev delete all
1119     set y 2
1120     code2canvas $code .cp.report.abbrev 5 y {} 0 {}
1121     manyset [.cp.report.abbrev bbox all] minx dummy maxx dummy
1122     .cp.report.abbrev configure -width [expr {$maxx-$minx+4}]
1123
1124     glset report_code $code
1125     show-report-decode $code
1126
1127     set kk "$islandname $code"
1128     upvar #0 found($kk) k
1129
1130     .cp.report.list delete 0 end
1131
1132     foreach entry $k {
1133         manyset $entry vid name owner
1134         lappend owned($owner) $name
1135     }
1136
1137     foreach owner [lsort [array names owned]] {
1138         if {[string length $owner]} {
1139             set owndesc "$owner's"
1140         } else {
1141             set owndesc "Owner unknown"
1142         }
1143         .cp.report.list insert end "$owndesc:"
1144         foreach name $owned($owner) {
1145             .cp.report.list insert end " $name"
1146         }
1147     }
1148 }
1149
1150 proc zoom {extail} {
1151     global scale canvas
1152     set nscale [expr "\$scale $extail"]
1153     debug "ZOOM $scale $nscale"
1154     if {$nscale < 1 || $nscale > 200} return
1155     set scale $nscale
1156     draw
1157 }
1158
1159 proc invoke_acquire {} {
1160     global clipboard errorInfo
1161     set old $clipboard
1162
1163     if {[catch {
1164         set clipboard [clipboard get]
1165     } emsg]} {
1166         parser-control-failed-unexpected .cp.ctrl.acquire acquire \
1167             $emsg "fetching clipboard:\n\n$errorInfo"
1168         return
1169     }
1170
1171     reparse acquire \
1172         clipboard $old "Clipboard contents:" { acquired ok } { no vessels } {
1173             parse-clipboard
1174         } {
1175             display-note-infos
1176         }
1177     draw
1178 }
1179
1180 proc invoke_notes {} {
1181     global notes_data errorInfo notes_loc
1182     set old $notes_data
1183     
1184     if {[catch {
1185         load-notes
1186     } emsg]} {
1187         parser-control-failed-unexpected .cp.ctrl.notes notes \
1188             $emsg "loading $notes_loc:\n\n$errorInfo"
1189         return
1190     }
1191
1192     reparse notes \
1193         notes_data $old "Vessel notes:" "loaded ok" { no notes } {
1194             parse-notes
1195             parse-clipboard
1196         } {
1197             display-note-infos
1198         }
1199     draw
1200 }
1201
1202 #---------- main program ----------
1203
1204 parseargs
1205 argdefaults
1206 httpclientsetup where-vessels
1207 info-cache-update
1208 vesselclasses-init
1209 load-chart
1210 widgets-setup
1211 make-filters
1212
1213 set notes_data {}
1214 if {[catch { parse-clipboard } emsg]} {
1215     puts stderr "$emsg\n$errorInfo"
1216     exit 1
1217 }
1218 after idle invoke_notes
1219
1220 draw
1221
1222 # rsync -r --exclude=\*~ yarrg/icons/. ijackson@chiark.greenend.org.uk:/home/ftp/users/ijackson/yarrg/vessel-info/.