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