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