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