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