chiark / gitweb /
where-vessels WIP icons
[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 "99" $c]
696         }
697
698         set stackx $x
699         incr stackx 2
700         set tid [canvas-horiz-stack stackx $y \
701                  text -anchor nw -font fixed -text $qty]
702         incr stackx -1
703         canvas-horiz-stack stackx [expr {$y+1}] \
704             image -anchor nw -image ship-icon/$vc_code2abbrev([lindex [split $code _] 1])
705         incr stackx
706         canvas-horiz-stack stackx $y \
707             text -anchor nw -font fixed -text $text
708                 
709         set bbox [$canvas bbox $tid]
710         set ny [lindex $bbox 3]
711         puts "$tid $bbox"
712         set bid [$canvas create rectangle \
713                      $x $y $stackx $ny \
714                      -fill white]
715
716         set y $ny
717         $canvas lower $bid $tid
718
719         $canvas bind $tid <ButtonPress> [list show-report $islandname $code]
720         $canvas bind $bid <ButtonPress> [list show-report $islandname $code]
721         manyset $bbox dummy dummy dummy y
722 #       debug "NEW Y $y"
723     }
724
725     panner::updatecanvas-bbox .cp.ctrl.pan
726 }
727
728
729 #---------- parser error reporting ----------
730
731 proc parser-control-create {w base invokebuttontext etl_title} {
732     frame $w
733     button $w.do -text $invokebuttontext -command invoke_$base
734
735     frame $w.resframe -width 120 -height 32
736     button $w.resframe.res -text {} -anchor nw \
737         -padx 1 -pady 1 -borderwidth 0 -justify left
738     glset deffont_$base [$w.resframe.res cget -font]
739     place $w.resframe.res -relx 0.5 -y 0 -anchor n
740
741     pack $w.do -side top
742     pack $w.resframe -side top -expand y -fill both
743
744     set eb .err_$base
745     toplevel $eb
746     wm withdraw $eb
747     wm title $eb "where-vessels - $etl_title"
748
749     label $eb.title -text $etl_title
750     pack $eb.title -side top
751
752     button $eb.close -text Close -command [list wm withdraw $eb]
753     pack $eb.close -side bottom
754
755     frame $eb.emsg -bd 2 -relief groove
756     label $eb.emsg.lab -text "Error:"
757     text $eb.emsg.text -height 1
758     pack $eb.emsg.text -side bottom
759     pack $eb.emsg.lab -side left
760
761     pack $eb.emsg -side top -pady 2
762
763     frame $eb.text -bd 2 -relief groove
764     pack $eb.text -side bottom -pady 2
765     
766     label $eb.text.lab
767
768     text $eb.text.text -width 85 \
769         -xscrollcommand [list $eb.text.xscroll set] \
770         -yscrollcommand [list $eb.text.yscroll set]
771     $eb.text.text tag configure error \
772         -background red -foreground white
773
774     scrollbar $eb.text.xscroll -orient horizontal \
775         -command [list $eb.text.text xview]
776     scrollbar $eb.text.yscroll -orient vertical \
777         -command [list $eb.text.text yview]
778
779     grid configure $eb.text.lab -row 0 -column 0 -sticky w
780     grid configure $eb.text.text -row 1 -column 0
781     grid configure $eb.text.yscroll -sticky ns -row 1 -column 1
782     grid configure $eb.text.xscroll -sticky ew -row 2 -column 0
783 }
784
785 proc parser-control-ok-core {w base background show} {
786     debug "parser-control-ok-core $w $base $background $show"
787     upvar #0 deffont_$base deffont
788     $w.resframe.res configure \
789         -background $background -disabledforeground black -font $deffont \
790         -state disabled -command {} \
791         -text $show
792 }    
793 proc parser-control-ok {w base show} {
794     parser-control-ok-core $w $base green $show
795 }
796 proc parser-control-none {w base show} {
797     parser-control-ok-core $w $base blue $show
798 }
799 proc parser-control-failed-core {w base foreground background smallfont
800                                  tiny summary fulldesc fulldata} {
801     debug "parser-control-failed-core $w $base $summary $fulldesc"
802     upvar #0 deffont_$base deffont
803     set eb .err_$base
804
805     $eb.emsg.text delete 0.0 end
806     $eb.emsg.text insert end $summary
807
808     $eb.text.lab configure -text $fulldesc
809     $eb.text.text delete 0.0 end
810     $eb.text.text insert end $fulldata
811
812     regsub -all {.{18}} $tiny "&\n" ewrap
813
814     if {$smallfont} {
815         set font fixed
816     } else {
817         set font $deffont
818     }
819
820     $w.resframe.res configure \
821         -background $background -foreground $foreground -font $font \
822         -state normal -command [list wm deiconify $eb] \
823         -text $ewrap
824 }
825     
826 proc parser-control-failed-expected {w base emsg lno ei fulldesc newdata} {
827     set eb .err_$base
828
829     set line [lindex [split $ei "\n"] 0]
830     debug "parser-control-failed-expected: $w $base: $lno: $emsg\n $line"
831
832     parser-control-failed-core $w $base \
833         white red 1 \
834         "err: [string trim $emsg]: \"$line\"" \
835         "at line $lno: $emsg" \
836         $fulldesc $newdata
837
838     $eb.text.text tag add error $lno.0 $lno.end
839     $eb.text.text see $lno.0    
840 }
841 proc parser-control-failed-unexpected {w base emsg ei} {
842     global errorInfo
843     parser-control-failed-core $w $base \
844         black yellow 1 \
845         $emsg $emsg "Details and stack trace:" $ei
846 }
847
848 proc reparse {base varname old fulldesc okshow noneshow parse ok} {
849     upvar #0 $varname var
850     manyset [errexpect-catch {
851         uplevel 1 $parse
852         if {[string length [string trim $var]]} {
853             parser-control-ok .cp.ctrl.$base $base $okshow
854         } else {
855             parser-control-none .cp.ctrl.$base $base $noneshow
856         }
857     }] failed emsg lno ei
858     if {$failed} {
859         parser-control-failed-expected .cp.ctrl.$base $base \
860             $emsg $lno $ei $fulldesc $var
861         set var $old
862         uplevel 1 $parse
863     } else {
864         uplevel 1 $ok
865     }
866 }
867
868 #---------- main user interface ----------
869
870 proc widgets-setup {} {
871     global canvas debug pirate ocean
872
873     wm geometry . 1024x480
874     wm title . "where-vessels - $pirate on the $ocean ocean"
875
876     #----- map -----
877
878     frame .f -border 1 -relief groove
879     set canvas .f.c
880     canvas $canvas
881     pack $canvas -expand 1 -fill both
882     pack .f -expand 1 -fill both -side left
883
884     #----- control panels and filter -----
885
886     frame .cp
887     frame .filter -relief groove -bd 2
888     pack .cp .filter -side top
889
890     label .filter.title -text Filter
891     grid configure .filter.title -row 0 -column 0 -columnspan 2
892
893     #----- control panel -----
894
895     frame .cp.ctrl
896     pack .cp.ctrl -side left -anchor n
897
898     debug "BBOX [$canvas bbox all]"
899
900     panner::canvas-scroll-bbox .f.c
901     panner::create .cp.ctrl.pan .f.c 120 120 $debug
902
903     pack .cp.ctrl.pan -side top -pady 10 -padx 5
904     frame .cp.ctrl.zoom
905     pack .cp.ctrl.zoom -side top
906
907     button .cp.ctrl.zoom.out -text - -font {Courier 16} -command {zoom /2}
908     button .cp.ctrl.zoom.in  -text + -font {Courier 16} -command {zoom *2}
909     pack .cp.ctrl.zoom.out .cp.ctrl.zoom.in -side left
910
911     parser-control-create .cp.ctrl.acquire \
912         acquire Acquire \
913         "Clipboard parsing error" \
914         
915     pack .cp.ctrl.acquire -side top -pady 2
916
917     parser-control-create .cp.ctrl.notes \
918         notes "Reload notes" \
919         "Vessel notes loading report" \
920         
921     pack .cp.ctrl.notes -side top -pady 2
922
923     #----- decoding etc. report -----
924
925     frame .cp.report
926     pack .cp.report -side left -anchor n
927
928     label .cp.report.island -text { }
929
930     frame .cp.report.abbrev -background black
931     glset report_abbrev {         }
932     entry .cp.report.abbrev.abbrev -state readonly \
933         -textvariable report_abbrev \
934         -borderwidth 0 -relief flat -width 0 \
935         -highlightbackground white \
936         -readonlybackground white -foreground black
937     pack .cp.report.abbrev.abbrev -side left -padx 1 -pady 1
938
939     frame .cp.report.code
940     label .cp.report.code.lab -text Code:
941     glset report_code { }
942     entry .cp.report.code.code -state readonly \
943         -textvariable report_code -width 15
944     pack .cp.report.code.lab .cp.report.code.code -side left
945     frame .cp.report.details -bd 2 -relief groove -padx 2 -pady 2
946
947     listbox .cp.report.list -height 5
948
949     pack .cp.report.island .cp.report.abbrev .cp.report.details \
950         .cp.report.list .cp.report.code -side top
951     pack configure .cp.report.details -fill x
952
953     foreach sw {inport class subclass lock own xabbrev} {
954         label .cp.report.details.$sw -text { }
955         pack .cp.report.details.$sw -side top -anchor w
956     }
957 }
958
959 proc report-set {sw val} { .cp.report.details.$sw configure -text $val }
960
961 proc show-report {islandname code} {
962     .cp.report.island configure -text $islandname
963     glset report_code $code
964     glset report_abbrev [code2abbrev $code]
965
966     show-report-decode $code
967
968     set kk "$islandname $code"
969     upvar #0 found($kk) k
970
971     .cp.report.list delete 0 end
972
973     foreach entry $k {
974         manyset $entry vid name
975         .cp.report.list insert end $name
976     }
977 }
978
979 proc zoom {extail} {
980     global scale canvas
981     set nscale [expr "\$scale $extail"]
982     debug "ZOOM $scale $nscale"
983     if {$nscale < 1 || $nscale > 200} return
984     set scale $nscale
985     draw
986 }
987
988 proc invoke_acquire {} {
989     global clipboard errorInfo
990     set old $clipboard
991
992     if {[catch {
993         set clipboard [clipboard get]
994     } emsg]} {
995         parser-control-failed-unexpected .cp.ctrl.acquire acquire \
996             $emsg "fetching clipboard:\n\n$errorInfo"
997         return
998     }
999
1000     reparse acquire \
1001         clipboard $old "Clipboard contents:" { acquired ok } { no vessels } {
1002             parse-clipboard
1003         } {
1004             display-note-infos
1005         }
1006     draw
1007 }
1008
1009 proc invoke_notes {} {
1010     global notes_data errorInfo notes_loc
1011     set old $notes_data
1012     
1013     if {[catch {
1014         load-notes
1015     } emsg]} {
1016         parser-control-failed-unexpected .cp.ctrl.notes notes \
1017             $emsg "loading $notes_loc:\n\n$errorInfo"
1018         return
1019     }
1020
1021     reparse notes \
1022         notes_data $old "Vessel notes:" "loaded ok" { no notes } {
1023             parse-notes
1024             parse-clipboard
1025         } {
1026             display-note-infos
1027         }
1028     draw
1029 }
1030
1031 #---------- main program ----------
1032
1033 vesselclasses-init
1034
1035 parseargs
1036 argdefaults
1037 httpclientsetup where-vessels
1038 load-chart
1039 widgets-setup
1040 make-filters
1041
1042 set notes_data {}
1043 if {[catch { parse-clipboard } emsg]} {
1044     puts stderr "$emsg\n$errorInfo"
1045     exit 1
1046 }
1047 after idle invoke_notes
1048
1049 draw