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