chiark / gitweb /
c382c6a4b92f913218c2e6c73e40401723a19feb
[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     }
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] warnings"
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 .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         warfrig         im      wf      {War Frigate}
258         merchgal        jm      mg      {Merchant Galleon}
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     }
268 }
269
270 proc code2abbrev-lock {lockown} {
271     manyset [split $lockown ""] lock notown
272     append abbrev [lindex {* + -} $lock]
273     append abbrev [lindex {= - ?} [regsub {\D} $notown 2]]
274 }    
275
276 proc code2abbrev {code} {
277     global vc_code2abbrev
278
279     manyset [split $code _] inport class subclass lockown xabbrev
280
281     set abbrev {}
282     append abbrev [lindex {? {}} $inport]
283     append abbrev $vc_code2abbrev($class)
284     append abbrev $subclass
285     append abbrev [code2abbrev-lock $lockown]
286     append abbrev $xabbrev
287
288     debug "CODE2ABBREV $code $abbrev"
289     return $abbrev
290 }
291
292 proc show-report-decode {code} {
293     global vc_code2full
294
295     manyset [split $code _] inport classcode subclass lockown xabbrev
296     manyset [split $lockown ""] lock notown
297     
298     report-set inport [lindex {{At Sea} {In port}} $inport]
299     report-set class $vc_code2full($classcode)
300
301     switch -exact $subclass {
302         {} { report-set subclass {Ordinary} }
303         F { report-set subclass {"Frost class"} }
304         default { report-set subclass "Subclass \"$subclass\"" }
305     }
306
307     report-set lock [lindex {
308         {Battle ready} {Unlocked} {Locked}
309     } $lock]
310
311     switch -exact $notown {
312         0 { report-set own "Yours" }
313         1 { report-set own "Other pirate's" }
314         U { report-set own "Owner not known" }
315         M { report-set own "Missing from notes" }
316         default { report-set own "?? $notown" }
317     }
318
319     if {[string length $xabbrev]} {
320         report-set xabbrev "Notes flags: $xabbrev"
321     } else {
322         report-set xabbrev "No flags in notes"
323     }
324 }
325
326 #---------- filtering ----------
327
328 set filters {}
329
330 #proc make-size-filter {minmax minmaxdesc} {
331 #    set n [llength $vc_codes]
332 #    $w configure 
333
334 #    make-filter size${minmax} "$minmaxdesc size" scale \
335 #       [list \
336 #            -tickinterval 0 \
337 #            -variable filter_size{$minmax} \
338 #            -from 0 -to [expr {$n-1}] \
339 #            -resolution 1 \
340 #            -length [expr {$n*5}] \
341 #            ]
342
343
344 proc filter-values/size {} { global vc_codes; return $vc_codes }
345 proc filter-map/size {code} { upvar #0 vc_code2abbrev($code) abb; return $abb }
346 proc filter-default/size {code} { return 1 }
347
348 proc filter-values/lockown {} {
349     foreach lv {0 1 2} {
350         foreach ov {0 1 X} {
351             lappend vals "$lv$ov"
352         }
353     }
354     return $vals
355 }
356 proc filter-map/lockown {lockown} { return [code2abbrev-lock $lockown] }
357 proc filter-default/lockown {lockown} {
358     return [regexp {^[01]|^2[^1]} $lockown]
359 }
360
361 proc filter-validate/xabbre {re} {
362     if {[catch {
363         regexp -- $re {}
364     } emsg]} {
365         regsub {^.*:\s*} $emsg {} emsg
366         regsub {^.*(.{30})$} $emsg {\1} emsg
367         return $emsg
368     }
369     return {}
370 }
371
372 proc filter-tickbox-flip {fil} {
373     upvar #0 filter_$fil vars
374     set values [filter-values/$fil]
375     foreach val $values {
376         set vars($val) [expr {!$vars($val)}]
377     }
378     refilter-needed
379 }
380
381 proc make-tickbox-filter {fil label rows inrow} {
382     upvar #0 filter_$fil vars
383     set fw [make-filter tickbox $fil $label frame]
384     set values [filter-values/$fil]
385     set nvalues [llength $values]
386     if {!$inrow} {
387         set inrow [expr {($nvalues + $rows) / $rows}]
388     }
389
390     for {set ix 0} {$ix < $nvalues} {incr ix} {
391         set val [lindex $values $ix]
392         set vars($val) [filter-default/$fil $val]
393         checkbutton $fw.$ix -variable filter_${fil}($val) \
394             -text [filter-map/$fil $val] -font fixed \
395             -command refilter-needed
396         grid configure $fw.$ix -sticky sw \
397             -row [expr {$ix / $inrow}] \
398             -column [expr {$ix % $inrow}]
399     }
400     button $fw.invert -text flip -command [list filter-tickbox-flip $fil] \
401         -padx 0 -pady 0
402     grid configure $fw.invert -sticky se \
403         -row [expr {$rows-1}] \
404         -column [expr {$inrow-1}]
405 }
406
407 proc entry-filter-changed {fw fil n1 n2 op} {
408     global errorInfo
409     upvar #0 filter_$fil realvar
410     upvar #0 filterentered_$fil entryvar
411     global def_background
412     debug "entry-filter-changed $fw $fil $entryvar"
413     if {[catch {
414         set error [filter-validate/$fil $entryvar]
415         if {[string length $error]} {
416             $fw.error configure -text $error -foreground white -background red
417         } else {
418             $fw.error configure -text { } -background $def_background
419             set realvar $entryvar
420             refilter-needed
421         }
422     } emsg]} {
423         puts stderr "FILTER CHECK ERROR $emsg $errorInfo"
424     }
425 }
426
427 proc make-entry-filter {fil label def} {
428     global filterentered_$fil
429     upvar #0 filter_$fil realvar
430     set realvar $def
431     set fw [make-filter entry $fil $label frame]
432     entry $fw.entry -textvariable filterentered_$fil
433     label $fw.error
434     glset def_background [$fw.error cget -background]
435     trace add variable filterentered_$fil write \
436         [list entry-filter-changed $fw $fil]
437     pack $fw.entry $fw.error -side top -anchor w
438 }
439
440 proc refilter-needed {} {
441     debug "REFILTER NEEDED"
442 }
443
444 proc make-filter {kind fil label ekind} {
445     global filters
446     label .filter.lab_$fil -text $label -justify left
447     $ekind .filter.$fil
448     lappend filters [list $kind $fil]
449     set nfilters [llength $filters]
450     grid configure .filter.lab_$fil -row $nfilters -column 0 -sticky nw -pady 4
451     grid configure .filter.$fil -row $nfilters -column 1 -sticky w -pady 3
452     return .filter.$fil
453 }
454
455 proc make-filters {} {
456     make-tickbox-filter size Size 2 0
457     make-tickbox-filter lockown "Lock/\nowner" 2 6
458     make-entry-filter xabbre "Flags\n regexp" {}
459 }
460     
461 #---------- loading and parsing the clipboard (vessel locations) ----------
462
463 proc vessel {vin} {
464     global pirate notes_used note_missings newnotes
465     upvar 1 $vin vi
466
467     set codel {}
468     lappend codel [errexpect-arrayget-boolean vi inPort]
469
470     set gameclass [errexpect-arrayget vi vesselClass]
471     upvar #0 vc_game2code($gameclass) class
472     if {![info exists class]} { errexpect-error "unexpected vesselClass"}
473     lappend codel $class
474
475     set subclass [errexpect-arrayget vi vesselSubclass]
476     switch -exact $subclass {
477         null            { lappend codel {} }
478         icy             { lappend codel F }
479         default         { lappend codel ($subclass) }
480     }
481
482     switch -exact [errexpect-arrayget vi isLocked]/[ \
483                    errexpect-arrayget vi isBattleReady] {
484         true/false      { set lock 2 }
485         false/false     { set lock 1 }
486         false/true      { set lock 0 }
487         default         { errexpect-error "unexpected isLocked/isBattleReady" }
488     }
489
490     set vid [errexpect-arrayget vi vesselId]
491     upvar #0 notes($vid) note
492     set realname [errexpect-arrayget vi vesselName]
493     set island [errexpect-arrayget vi islandName]
494
495     set owner {}
496     set xabbrev {}
497     if {[info exists note]} {
498         manyset $note lno notename owner xabbrev
499         if {[string compare -nocase $realname $notename]} {
500             note-info $lno $vid $realname $island \
501                 "notes say name is $notename"
502         }
503         if {[string length $owner]} {
504             if {![string compare $owner $pirate]} {
505                 set notown 0
506             } else {
507                 set notown 1
508             }
509         } else {
510             set notown U
511         }
512         append abbrev $xabbrev
513         set notes_used($vid) 1
514
515     } else {
516         set notown M
517         lappend note_missings [list $island $realname $vid]
518     }
519
520     lappend codel "$lock$notown" $xabbrev
521     lappend newnotes [list $vid $realname $owner $xabbrev]
522     set kk "$island [join $codel _]"
523     upvar #0 found($kk) k
524     lappend k [list $vid $realname]
525  
526     debug "CODED $kk $vid $realname"
527 }
528
529 set clipboard {}
530 proc parse-clipboard {} {
531     global clipboard found notes notes_used newnotes
532
533     catch { unset found }
534     catch { unset notes_used }
535     glset note_infos {}
536     glset note_missings {}
537
538     set newnotes {}
539     
540     set itemre { (\w+) = ([^=]*) }
541     set manyitemre "^\\\[ $itemre ( (?: ,\\ $itemre)* ) \\]\$"
542     debug $manyitemre
543
544     set lno 0
545     foreach l [split $clipboard "\n"] {
546         incr lno
547         errexpect-setline $lno $l
548         if {![string length $l]} continue
549         catch { unset vi }
550         while 1 {
551                 if {![regexp -expanded $manyitemre $l dummy \
552                         thiskey thisval rhs]} {
553                     errexpect-error "badly formatted"
554                 }
555                 set vi($thiskey) $thisval
556                 if {![string length $rhs]} break
557                 regsub {^, } $rhs {} rhs
558                 set l "\[$rhs\]"
559         }
560         vessel vi
561     }
562
563     if {[llength $newnotes]} {
564         foreach vid [lsort [array names notes]] {
565             if {![info exists notes_used($vid)]} {
566                 manyset $notes($vid) lno notename
567                 note-info $lno $vid $notename {} \
568                     "vessel in notes no longer found"
569             }
570         }
571     }
572 }
573
574 proc load-clipboard-file {fn} {
575     set f [open $fn]
576     glset clipboard [read $f]
577     close $f
578 }
579
580
581 #---------- loading and parsing the chart ----------
582
583 proc load-chart {} {
584     global chart scraper
585     debug "FETCHING CHART"
586     set chart [eval exec $scraper [list | perl -we {
587         use strict;
588         use CommodsScrape;
589         use IO::File;
590         use IO::Handle;
591         yppedia_chart_parse(\*STDIN, (new IO::File ">/dev/null"),
592                 sub { sprintf "%d %d", @_; },
593                 sub { printf "archlabel %d %d %s\n", @_; },
594                 sub { printf "island %s %s\n", @_; },
595                 sub { printf "league %s %s %s.\n", @_; },
596                 sub { printf STDERR "warning: %s: incomprehensible: %s", @_; }
597                         );
598         STDOUT->error and die $!;
599     }]]
600 }
601
602
603 set scale 16
604
605 proc coord {c} {
606         global scale
607         return [expr {$c * $scale}]
608 }
609
610 proc chart-got/archlabel {args} { }
611 proc chart-got/island {x y args} {
612 #       debug "ISLE $x $y $args"
613         global canvas isleloc
614         set isleloc($args) [list $x $y]
615         set sz 5
616 #       $canvas create oval \
617 #               [expr {[coord $x] - $sz}] [expr {[coord $y] - $sz}] \
618 #               [expr {[coord $x] + $sz}] [expr {[coord $y] + $sz}] \
619 #               -fill blue
620         $canvas create text [coord $x] [coord $y] \
621                 -text $args -anchor s
622 }
623 proc chart-got/league {x1 y1 x2 y2 kind} {
624 #       debug "LEAGUE $x1 $y1 $x2 $y2 $kind"
625         global canvas
626         set l [$canvas create line \
627                 [coord $x1] [coord $y1] \
628                 [coord $x2] [coord $y2]]
629         if {![string compare $kind .]} {
630                 $canvas itemconfigure $l -dash .
631         }
632 }
633
634 proc draw {} {
635     global chart found isleloc canvas
636     
637     $canvas delete all
638
639     foreach l [split $chart "\n"] {
640 #       debug "CHART-GOT $l"
641         set proc [lindex $l 0]
642         eval chart-got/$proc [lrange $l 1 end]
643     }
644
645     set lastislandname {}
646     foreach key [lsort [array names found]] {
647         set c [llength $found($key)]
648 #       debug "SHOWING $key $c"
649         regexp {^(.*) (\S+)$} $key dummy islandname code
650
651         set abbrev [code2abbrev $code]
652         
653         if {[string compare $lastislandname $islandname]} {
654                 manyset $isleloc($islandname) x y
655                 set x [coord $x]
656                 set y [coord $y]
657                 set lastislandname $islandname
658 #               debug "START Y $y"
659         }
660         set text $abbrev
661         regsub -all {[0-9]} $text {} text
662         if {$c > 1} {
663                 set text [format "%2d%s" $c $text]
664         } else {
665                 set text [format "  %s" $text]
666         }
667         set id [$canvas create text $x $y \
668                 -anchor nw -font fixed \
669                 -text $text]
670         set bbox [$canvas bbox $id]
671         set bid [eval $canvas create rectangle $bbox -fill white]
672         $canvas lower $bid $id
673         $canvas bind $id <ButtonPress> [list show-report $islandname $code]
674         $canvas bind $bid <ButtonPress> [list show-report $islandname $code]
675         manyset $bbox dummy dummy dummy y
676 #       debug "NEW Y $y"
677     }
678
679     panner::updatecanvas-bbox .ctrl.pan
680 }
681
682
683 #---------- parser error reporting ----------
684
685 proc parser-control-create {w base invokebuttontext etl_title} {
686     frame $w
687     button $w.do -text $invokebuttontext -command invoke_$base
688
689     frame $w.resframe -width 120 -height 32
690     button $w.resframe.res -text {} -anchor nw \
691         -padx 1 -pady 1 -borderwidth 0 -justify left
692     glset deffont_$base [$w.resframe.res cget -font]
693     place $w.resframe.res -relx 0.5 -y 0 -anchor n
694
695     pack $w.do -side top
696     pack $w.resframe -side top -expand y -fill both
697
698     set eb .err_$base
699     toplevel $eb
700     wm withdraw $eb
701     wm title $eb "where-vessels - $etl_title"
702
703     label $eb.title -text $etl_title
704     pack $eb.title -side top
705
706     button $eb.close -text Close -command [list wm withdraw $eb]
707     pack $eb.close -side bottom
708
709     frame $eb.emsg -bd 2 -relief groove
710     label $eb.emsg.lab -text "Error:"
711     text $eb.emsg.text -height 1
712     pack $eb.emsg.text -side bottom
713     pack $eb.emsg.lab -side left
714
715     pack $eb.emsg -side top -pady 2
716
717     frame $eb.text -bd 2 -relief groove
718     pack $eb.text -side bottom -pady 2
719     
720     label $eb.text.lab
721
722     text $eb.text.text -width 85 \
723         -xscrollcommand [list $eb.text.xscroll set] \
724         -yscrollcommand [list $eb.text.yscroll set]
725     $eb.text.text tag configure error \
726         -background red -foreground white
727
728     scrollbar $eb.text.xscroll -orient horizontal \
729         -command [list $eb.text.text xview]
730     scrollbar $eb.text.yscroll -orient vertical \
731         -command [list $eb.text.text yview]
732
733     grid configure $eb.text.lab -row 0 -column 0 -sticky w
734     grid configure $eb.text.text -row 1 -column 0
735     grid configure $eb.text.yscroll -sticky ns -row 1 -column 1
736     grid configure $eb.text.xscroll -sticky ew -row 2 -column 0
737 }
738
739 proc parser-control-ok-core {w base background show} {
740     debug "parser-control-ok-core $w $base $background $show"
741     upvar #0 deffont_$base deffont
742     $w.resframe.res configure \
743         -background $background -disabledforeground black -font $deffont \
744         -state disabled -command {} \
745         -text $show
746 }    
747 proc parser-control-ok {w base show} {
748     parser-control-ok-core $w $base green $show
749 }
750 proc parser-control-none {w base show} {
751     parser-control-ok-core $w $base blue $show
752 }
753 proc parser-control-failed-core {w base foreground background smallfont
754                                  tiny summary fulldesc fulldata} {
755     debug "parser-control-failed-core $w $base $summary $fulldesc"
756     upvar #0 deffont_$base deffont
757     set eb .err_$base
758
759     $eb.emsg.text delete 0.0 end
760     $eb.emsg.text insert end $summary
761
762     $eb.text.lab configure -text $fulldesc
763     $eb.text.text delete 0.0 end
764     $eb.text.text insert end $fulldata
765
766     regsub -all {.{18}} $tiny "&\n" ewrap
767
768     if {$smallfont} {
769         set font fixed
770     } else {
771         set font $deffont
772     }
773
774     $w.resframe.res configure \
775         -background $background -foreground $foreground -font $font \
776         -state normal -command [list wm deiconify $eb] \
777         -text $ewrap
778 }
779     
780 proc parser-control-failed-expected {w base emsg lno ei fulldesc newdata} {
781     set eb .err_$base
782
783     set line [lindex [split $ei "\n"] 0]
784     debug "parser-control-failed-expected: $w $base: $lno: $emsg\n $line"
785
786     parser-control-failed-core $w $base \
787         white red 1 \
788         "err: [string trim $emsg]: \"$line\"" \
789         "at line $lno: $emsg" \
790         $fulldesc $newdata
791
792     $eb.text.text tag add error $lno.0 $lno.end
793     $eb.text.text see $lno.0    
794 }
795 proc parser-control-failed-unexpected {w base emsg ei} {
796     global errorInfo
797     parser-control-failed-core $w $base \
798         black yellow 1 \
799         $emsg $emsg "Details and stack trace:" $ei
800 }
801
802 proc reparse {base varname old fulldesc okshow noneshow parse ok} {
803     upvar #0 $varname var
804     manyset [errexpect-catch {
805         uplevel 1 $parse
806         if {[string length [string trim $var]]} {
807             parser-control-ok .ctrl.$base $base $okshow
808         } else {
809             parser-control-none .ctrl.$base $base $noneshow
810         }
811     }] failed emsg lno ei
812     if {$failed} {
813         parser-control-failed-expected .ctrl.$base $base \
814             $emsg $lno $ei $fulldesc $var
815         set var $old
816         uplevel 1 $parse
817     } else {
818         uplevel 1 $ok
819     }
820 }
821
822 #---------- main user interface ----------
823
824 proc widgets-setup {} {
825     global canvas debug pirate ocean
826
827     wm geometry . 1024x480
828     wm title . "where-vessels - $pirate on the $ocean ocean"
829
830     #----- map -----
831
832     frame .f -border 1 -relief groove
833     set canvas .f.c
834     canvas $canvas
835     pack $canvas -expand 1 -fill both
836     pack .f -expand 1 -fill both -side left
837
838     #----- filter -----
839
840     frame .filter -relief groove -bd 2
841     pack .filter -side bottom
842
843     label .filter.title -text Filter
844     grid configure .filter.title -row 0 -column 0 -columnspan 2
845
846     #----- control panel -----
847
848     frame .ctrl
849     pack .ctrl -side left -anchor n
850
851     debug "BBOX [$canvas bbox all]"
852
853     panner::canvas-scroll-bbox .f.c
854     panner::create .ctrl.pan .f.c 120 120 $debug
855
856     pack .ctrl.pan -side top -pady 10 -padx 5
857     frame .ctrl.zoom
858     pack .ctrl.zoom -side top
859
860     button .ctrl.zoom.out -text - -font {Courier 16} -command {zoom /2}
861     button .ctrl.zoom.in  -text + -font {Courier 16} -command {zoom *2}
862     pack .ctrl.zoom.out .ctrl.zoom.in -side left
863
864     parser-control-create .ctrl.acquire \
865         acquire Acquire \
866         "Clipboard parsing error" \
867         
868     pack .ctrl.acquire -side top -pady 2
869
870     parser-control-create .ctrl.notes \
871         notes "Reload notes" \
872         "Vessel notes loading report" \
873         
874     pack .ctrl.notes -side top -pady 2
875
876     #----- decoding etc. report -----
877
878     frame .report
879     pack .report -side left -anchor n
880
881     label .report.island -text { }
882
883     frame .report.abbrev -background black
884     glset report_abbrev {         }
885     entry .report.abbrev.abbrev -state readonly \
886         -textvariable report_abbrev \
887         -borderwidth 0 -relief flat -width 0 \
888         -highlightbackground white \
889         -readonlybackground white -foreground black
890     pack .report.abbrev.abbrev -side left -padx 1 -pady 1
891
892     frame .report.code
893     label .report.code.lab -text Code:
894     glset report_code { }
895     entry .report.code.code -state readonly -textvariable report_code -width 15
896     pack .report.code.lab .report.code.code -side left
897     frame .report.details -bd 2 -relief groove -padx 2 -pady 2
898
899     listbox .report.list -height 5
900
901     pack .report.island .report.abbrev .report.details \
902         .report.list .report.code -side top
903     pack configure .report.details -fill x
904
905     foreach sw {inport class subclass lock own xabbrev} {
906         label .report.details.$sw -text { }
907         pack .report.details.$sw -side top -anchor w
908     }
909 }
910
911 proc report-set {sw val} { .report.details.$sw configure -text $val }
912
913 proc show-report {islandname code} {
914     .report.island configure -text $islandname
915     glset report_code $code
916     glset report_abbrev [code2abbrev $code]
917
918     show-report-decode $code
919
920     set kk "$islandname $code"
921     upvar #0 found($kk) k
922
923     .report.list delete 0 end
924
925     foreach entry $k {
926         manyset $entry vid name
927         .report.list insert end $name
928     }
929 }
930
931 proc zoom {extail} {
932     global scale canvas
933     set nscale [expr "\$scale $extail"]
934     debug "ZOOM $scale $nscale"
935     if {$nscale < 1 || $nscale > 200} return
936     set scale $nscale
937     draw
938 }
939
940 proc invoke_acquire {} {
941     global clipboard errorInfo
942     set old $clipboard
943
944     if {[catch {
945         set clipboard [clipboard get]
946     } emsg]} {
947         parser-control-failed-unexpected .ctrl.acquire acquire \
948             $emsg "fetching clipboard:\n\n$errorInfo"
949         return
950     }
951
952     reparse acquire \
953         clipboard $old "Clipboard contents:" { acquired ok } { no vessels } {
954             parse-clipboard
955         } {
956             display-note-infos
957         }
958     draw
959 }
960
961 proc invoke_notes {} {
962     global notes_data errorInfo notes_loc
963     set old $notes_data
964     
965     if {[catch {
966         load-notes
967     } emsg]} {
968         parser-control-failed-unexpected .ctrl.notes notes \
969             $emsg "loading $notes_loc:\n\n$errorInfo"
970         return
971     }
972
973     reparse notes \
974         notes_data $old "Vessel notes:" "loaded ok" { no notes } {
975             parse-notes
976             parse-clipboard
977         } {
978             display-note-infos
979         }
980     draw
981 }
982
983 #---------- main program ----------
984
985 vesselclasses-init
986
987 parseargs
988 argdefaults
989 httpclientsetup where-vessels
990 load-chart
991 widgets-setup
992 make-filters
993
994 set notes_data {}
995 if {[catch { parse-clipboard } emsg]} {
996     puts stderr "$emsg\n$errorInfo"
997     exit 1
998 }
999 after idle invoke_notes
1000
1001 draw