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