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