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