chiark / gitweb /
where-vessels: icons for lock state too
[ypp-sc-tools.main.git] / yarrg / where-vessels
1 #!/usr/bin/wish
2 # show your vessels on a map
3
4 # This is part of ypp-sc-tools, a set of third-party tools for assisting
5 # players of Yohoho Puzzle Pirates.
6 #
7 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
8 #
9 # This program is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 #
22 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
23 # are used without permission.  This program is not endorsed or
24 # sponsored by Three Rings.
25
26
27
28 source yarrglib.tcl
29 source panner.tcl
30 package require http
31
32 #---------- general utilities ----------
33
34 set debug 0
35 proc debug {m} {
36     global debug
37     if {$debug} { puts "DEBUG $m" }
38 }
39
40 proc badusage {m} {
41     puts stderr "where-vessels: bad usage: $m"
42     exit 1
43 }
44
45 proc glset {n val} {
46     upvar #0 $n var
47     set var $val
48 }
49
50 #---------- expecting certain errors ----------
51
52 proc errexpect-setline {lno line} {
53     glset errexpect_lno $lno
54     glset errexpect_line $line
55 }
56
57 proc errexpect-error {m} {
58     global errexpect_line errexpect_lno
59     error $m "$errexpect_line\n" [list YARRG-ERREXPECT $errexpect_lno]
60 }
61
62 proc errexpect-arrayget {arrayvar key} {
63     upvar 1 $arrayvar av
64     upvar 1 ${arrayvar}($key) v
65     if {[info exists v]} { return $v }
66     errexpect-error "undefined $key"
67 }
68
69 proc errexpect-arrayget-boolean {arrayvar key} {
70     switch -exact [uplevel 1 [list errexpect-arrayget $arrayvar $key]] {
71         true    { return 1 }
72         false   { return 0 }
73         default { errexpect-error "unexpected $key" }
74     }
75 }
76
77 proc errexpect-catch {code} {
78     global errorInfo errorCode
79     set rc [catch {
80         uplevel 1 $code
81     } rv]
82     debug "ERREXPECT CATCH |$rc|$rv|$errorCode|$errorInfo|"
83     if {$rc==1 && ![string compare YARRG-ERREXPECT [lindex $errorCode 0]]} {
84         return [list 1 $rv [lindex $errorCode 1] $errorInfo]
85     } elseif {$rc==0} {
86         return [list 0 $rv]
87     } else {
88         return -code $rc -errorinfo $errorInfo -errorcode $errorCode $rv
89     }
90 }
91
92 #---------- argument parsing ----------
93
94 proc nextarg {} {
95     global ai argv
96     if {$ai >= [llength $argv]} {
97         badusage "option [lindex $argv [expr {$ai-1}]] needs a value"
98     }
99     set v [lindex $argv $ai]
100     incr ai
101     return $v
102 }
103
104 set notes_loc vessel-notes
105 set scraper {./yppedia-ocean-scraper --chart}
106
107 proc parseargs {} {
108     global ai argv
109     global debug scraper
110     set ai 0
111
112     while {[regexp {^\-} [set arg [lindex $argv $ai]]]} {
113         incr ai
114         switch -exact -- $arg {
115             -- { break }
116             --pirate { glset pirate [string totitle [nextarg]] }
117             --ocean { glset ocean [string totitle [nextarg]] }
118             --clipboard-file { load-clipboard-file [nextarg] }
119             --local-html-dir { lappend scraper --local-html-dir=[nextarg] }
120             --notes { glset notes_loc [nextarg] }
121             --debug { incr debug }
122             default { badusage "unknown option $arg" }
123         }
124     }
125     set argv [lrange $argv $ai end]
126     if {[llength $argv]} { badusage "non-option args not allowed" }
127 }
128
129 proc argdefaults {} {
130     global ocean notes_loc pirate scraper
131     if {![info exists ocean] || ![info exists pirate]} {
132         set cmd {./yarrg --find-window-only --quiet}
133         if {[info exists ocean]} { lappend cmd --ocean $ocean }
134         if {[info exists pirate]} { lappend cmd --pirate $pirate }
135         manyset [split [eval exec $cmd] " "] ocean pirate
136     }
137     lappend scraper $ocean
138 }
139
140
141 #---------- loading and parsing the vessel notes ----------
142
143 proc load-notes {} {
144     global notes_loc notes_data
145     if {[regexp {^\w+\:} $notes_loc]} {
146         update
147         debug "FETCHING NOTES $notes_loc"
148         set req [::http::geturl $notes_loc]
149         switch -glob [::http::status $req].[::http::ncode $req] {
150             ok.200 { }
151             ok.* { error "retrieving vessel-notes: [::http::code $req]" }
152             * { error "Retrieving vessel-notes: [::http::error $req]" }
153         }
154         set newdata [::http::data $req]
155         ::http::cleanup $req
156     } else {
157         debug "READING NOTES $notes_loc"
158         set vn [open $notes_loc]
159         set newdata [read $vn]
160         close $vn
161     }
162     set notes_data $newdata
163 }
164
165 proc parse-notes {} {
166     global notes_data notes
167     catch { unset notes }
168
169     set lno 0
170     foreach l [split $notes_data "\n"] {
171         incr lno
172         errexpect-setline $lno $l
173         set l [string trim $l]
174         if {![string length $l]} continue
175         if {[regexp {^\#} $l]} continue
176         if {![regexp -expanded \
177                   {^ (\d+) (?: \s+([^=]*?) )? \s* =
178                       (?: \s* (\S+)
179                        (?: \s+ (\S+) )?)? $} \
180                   $l dummy vid vname owner note]} {
181               errexpect-error "badly formatted"
182         }
183         set vname [string trim $vname]
184         if {[info exists notes($vid)]} {
185             errexpect-error "duplicate vesselid $vid"
186         }
187         set notes($vid) [list $lno $vname $owner $note]
188     }
189 }
190
191 proc note-info {lno vid name island description} {
192     global note_infos
193     lappend note_infos [list $lno $vid $name $island $description]
194 }
195
196 proc display-note-infos {} {
197     global note_infos note_missings notes
198
199     set nmissing [llength $note_missings]
200     debug "display-note-infos $nmissing [array size notes]"
201
202     if {[llength $note_infos]} {
203         set tiny "[llength $note_infos] 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         warfrig         im      wf      {War Frigate}
258         merchgal        jm      mg      {Merchant Galleon}
259         grandfrig       km      gf      {Grand Frigate}
260     }
261     set vc_codes {}
262     foreach {game code abbrev full} $vcl {
263         lappend vc_codes $code
264         set vc_game2code($game) $code
265         set vc_code2abbrev($code) $abbrev
266         set vc_code2full($code) $full
267         load-icon $abbrev
268     }
269
270     load-icon unlocked
271     load-icon locked
272     load-icon battle
273     load-icon borrow
274     load-icon query
275     load-icon ours
276     load-icon dot
277 }
278
279 proc load-icon {icon} {
280     image create bitmap icon/$icon -file icons/$icon.xbm
281 }
282
283 proc code2abbrev-lock {lockown} {
284     manyset [split $lockown ""] lock notown
285     append abbrev [lindex {* + -} $lock]
286     append abbrev [lindex {= - ?} [regsub {\D} $notown 2]]
287 }    
288
289 proc canvas-horiz-stack {xvar xoff y bind type args} {
290     upvar 1 $xvar x
291     upvar 1 canvas canvas
292     set id [eval $canvas create $type [expr {$x+$xoff}] $y $args]
293     set bbox [$canvas bbox $id]
294     set x [lindex $bbox 2]
295     $canvas bind $id <ButtonPress> $bind
296     return $id
297 }
298
299 proc code2canvas {code canvas x yvar qty qtylen bind} {
300     global vc_code2abbrev
301     upvar 1 $yvar y
302
303     manyset [split $code _] inport class subclass lockown xabbrev
304
305     set stackx $x
306     incr stackx 2
307     set imy [expr {$y+2}]
308
309     append qty [lindex {? {}} $inport]
310     set qty [format "%${qtylen}s" $qty]
311
312     set qtyid [canvas-horiz-stack stackx 0 $y $bind \
313                    text -anchor nw -font fixed -text $qty]
314
315     canvas-horiz-stack stackx -1 $imy $bind \
316             image -anchor nw -image icon/$vc_code2abbrev($class)
317
318     if {[string length $subclass]} {
319         canvas-horiz-stack stackx 0 $y $bind \
320             text -anchor nw -font fixed -text \
321             $subclass
322     }
323
324     manyset [split $lockown ""] lock notown
325
326     incr stackx
327     canvas-horiz-stack stackx 0 $imy $bind \
328         image -anchor nw -image icon/[lindex {battle dot locked} $lock]
329     incr stackx
330     canvas-horiz-stack stackx 0 $imy $bind \
331         image -anchor nw -image icon/[lindex {ours dot query} \
332                                           [regsub {\D} $notown 2]]
333     incr stackx
334     
335     if {[string length $xabbrev]} {
336         canvas-horiz-stack stackx 0 $y $bind \
337             text -anchor nw -font fixed -text \
338             $xabbrev
339     }
340     
341     set bbox [$canvas bbox $qtyid]
342     set ny [lindex $bbox 3]
343     set bid [$canvas create rectangle \
344                  $x $y $stackx $ny \
345                  -fill white]
346
347     set y $ny
348     $canvas lower $bid $qtyid
349
350     $canvas bind $bid <ButtonPress> $bind
351 }
352
353 proc show-report-decode {code} {
354     global vc_code2full
355
356     manyset [split $code _] inport classcode subclass lockown xabbrev
357     manyset [split $lockown ""] lock notown
358     
359     report-set inport [lindex {{At Sea} {In port}} $inport]
360     report-set class $vc_code2full($classcode)
361
362     switch -exact $subclass {
363         {} { report-set subclass {Ordinary} }
364         F { report-set subclass {"Frost class"} }
365         default { report-set subclass "Subclass \"$subclass\"" }
366     }
367
368     report-set lock [lindex {
369         {Battle ready} {Unlocked} {Locked}
370     } $lock]
371
372     switch -exact $notown {
373         0 { report-set own "Yours" }
374         1 { report-set own "Other pirate's" }
375         U { report-set own "Owner not known" }
376         M { report-set own "Missing from notes" }
377         default { report-set own "?? $notown" }
378     }
379
380     if {[string length $xabbrev]} {
381         report-set xabbrev "Notes flags: $xabbrev"
382     } else {
383         report-set xabbrev "No flags in notes"
384     }
385 }
386
387 #---------- filtering ----------
388
389 set filters {}
390
391 proc filter-values/size {} { global vc_codes; return $vc_codes }
392 proc filter-icon/size {code} {
393     upvar #0 vc_code2abbrev($code) abb
394     return icon/$abb
395 }
396 proc filter-default/size {code} { return 1 }
397 proc filter-says-yes/size {codel} {
398     set sizecode [lindex $codel 1]
399     upvar #0 filter_size($sizecode) yes
400     return $yes
401 }
402
403 proc filter-values/lockown {} {
404     foreach lv {0 1 2} {
405         foreach ov {0 1 X} {
406             lappend vals "$lv$ov"
407         }
408     }
409     return $vals
410 }
411 proc filter-map/lockown {lockown} { return [code2abbrev-lock $lockown] }
412 proc filter-default/lockown {lockown} {
413     return [regexp {^[01]|^2[^1]} $lockown]
414 }
415 proc filter-says-yes/lockown {codel} {
416     set lockown [lindex $codel 3]
417     regsub -all {\D} $lockown X lockown
418     upvar #0 filter_lockown($lockown) yes
419     return $yes
420 }
421
422 proc filter-validate/xabbre {re} {
423     if {[catch {
424         regexp -- $re {}
425     } emsg]} {
426         regsub {^.*:\s*} $emsg {} emsg
427         regsub {^.*(.{30})$} $emsg {\1} emsg
428         return $emsg
429     }
430     return {}
431 }
432 proc filter-says-yes/xabbre {codel} {
433     global filter_xabbre
434     set xabbrev [lindex $codel 4]
435     return [regexp -- $filter_xabbre $xabbrev]
436 }
437
438 proc filter-tickbox-flip {fil} {
439     upvar #0 filter_$fil vars
440     set values [filter-values/$fil]
441     foreach val $values {
442         set vars($val) [expr {!$vars($val)}]
443     }
444     redraw-needed
445 }
446
447 proc make-tickbox-filter {fil label rows inrow} {
448     upvar #0 filter_$fil vars
449     set fw [make-filter tickbox $fil $label frame]
450     set values [filter-values/$fil]
451     set nvalues [llength $values]
452     if {!$inrow} {
453         set inrow [expr {($nvalues + $rows) / $rows}]
454     }
455     set noicons [catch { info args filter-icon/$fil }]
456     for {set ix 0} {$ix < $nvalues} {incr ix} {
457         set val [lindex $values $ix]
458         set vars($val) [filter-default/$fil $val]
459         checkbutton $fw.$ix -variable filter_${fil}($val) \
460             -font fixed -command redraw-needed
461         if {!$noicons} {
462             $fw.$ix configure -image [filter-icon/$fil $val] -height 16
463         } else {
464             $fw.$ix configure -text [filter-map/$fil $val]
465         }
466         grid configure $fw.$ix -sticky sw \
467             -row [expr {$ix / $inrow}] \
468             -column [expr {$ix % $inrow}]
469     }
470     button $fw.invert -text flip -command [list filter-tickbox-flip $fil] \
471         -padx 0 -pady 0
472     grid configure $fw.invert -sticky se \
473         -row [expr {$rows-1}] \
474         -column [expr {$inrow-1}]
475 }
476
477 proc entry-filter-changed {fw fil n1 n2 op} {
478     global errorInfo
479     upvar #0 filter_$fil realvar
480     upvar #0 filterentered_$fil entryvar
481     global def_background
482     debug "entry-filter-changed $fw $fil $entryvar"
483     if {[catch {
484         set error [filter-validate/$fil $entryvar]
485         if {[string length $error]} {
486             $fw.error configure -text $error -foreground white -background red
487         } else {
488             $fw.error configure -text { } -background $def_background
489             set realvar $entryvar
490             redraw-needed
491         }
492     } emsg]} {
493         puts stderr "FILTER CHECK ERROR $emsg $errorInfo"
494     }
495 }
496
497 proc make-entry-filter {fil label def} {
498     global filterentered_$fil
499     upvar #0 filter_$fil realvar
500     set realvar $def
501     set fw [make-filter entry $fil $label frame]
502     entry $fw.entry -textvariable filterentered_$fil
503     label $fw.error
504     glset def_background [$fw.error cget -background]
505     trace add variable filterentered_$fil write \
506         [list entry-filter-changed $fw $fil]
507     pack $fw.entry $fw.error -side top -anchor w
508 }
509
510 proc make-filter {kind fil label ekind} {
511     global filters
512     label .filter.lab_$fil -text $label -justify left
513     $ekind .filter.$fil
514     lappend filters $fil
515     set nfilters [llength $filters]
516     grid configure .filter.lab_$fil -row $nfilters -column 0 -sticky nw -pady 4
517     grid configure .filter.$fil -row $nfilters -column 1 -sticky w -pady 3
518     return .filter.$fil
519 }
520
521 proc make-filters {} {
522     make-tickbox-filter size Size 2 0
523     make-tickbox-filter lockown "Lock/\nowner" 2 6
524     make-entry-filter xabbre "Flags\n regexp" {}
525 }
526
527 proc filters-say-yes {code} {
528     global filters
529     debug "filters-say-yes $code"
530     foreach fil $filters {
531         if {![filter-says-yes/$fil [split $code _]]} { return 0 }
532     }
533     return 1
534 }
535     
536 #---------- loading and parsing the clipboard (vessel locations) ----------
537
538 proc vessel {vin} {
539     global pirate notes_used note_missings newnotes
540     upvar 1 $vin vi
541
542     set codel {}
543     lappend codel [errexpect-arrayget-boolean vi inPort]
544
545     set gameclass [errexpect-arrayget vi vesselClass]
546     upvar #0 vc_game2code($gameclass) class
547     if {![info exists class]} { errexpect-error "unexpected vesselClass"}
548     lappend codel $class
549
550     set subclass [errexpect-arrayget vi vesselSubclass]
551     switch -exact $subclass {
552         null            { lappend codel {} }
553         icy             { lappend codel F }
554         default         { lappend codel ($subclass) }
555     }
556
557     switch -exact [errexpect-arrayget vi isLocked]/[ \
558                    errexpect-arrayget vi isBattleReady] {
559         true/false      { set lock 2 }
560         false/false     { set lock 1 }
561         false/true      { set lock 0 }
562         default         { errexpect-error "unexpected isLocked/isBattleReady" }
563     }
564
565     set vid [errexpect-arrayget vi vesselId]
566     upvar #0 notes($vid) note
567     set realname [errexpect-arrayget vi vesselName]
568     set island [errexpect-arrayget vi islandName]
569
570     set owner {}
571     set xabbrev {}
572     if {[info exists note]} {
573         manyset $note lno notename owner xabbrev
574         if {[string compare -nocase $realname $notename]} {
575             note-info $lno $vid $realname $island \
576                 "notes say name is $notename"
577         }
578         if {[string length $owner]} {
579             if {![string compare $owner $pirate]} {
580                 set notown 0
581             } else {
582                 set notown 1
583             }
584         } else {
585             set notown U
586         }
587         append abbrev $xabbrev
588         set notes_used($vid) 1
589
590     } else {
591         set notown M
592         lappend note_missings [list $island $realname $vid]
593     }
594
595     lappend codel "$lock$notown" $xabbrev
596     lappend newnotes [list $vid $realname $owner $xabbrev]
597     set kk "$island [join $codel _]"
598     upvar #0 found($kk) k
599     lappend k [list $vid $realname]
600  
601     debug "CODED $kk $vid $realname"
602 }
603
604 set clipboard {}
605 proc parse-clipboard {} {
606     global clipboard found notes notes_used newnotes
607
608     catch { unset found }
609     catch { unset notes_used }
610     glset note_infos {}
611     glset note_missings {}
612
613     set newnotes {}
614     
615     set itemre { (\w+) = ([^=]*) }
616     set manyitemre "^\\\[ $itemre ( (?: ,\\ $itemre)* ) \\]\$"
617     debug $manyitemre
618
619     set lno 0
620     foreach l [split $clipboard "\n"] {
621         incr lno
622         errexpect-setline $lno $l
623         if {![string length $l]} continue
624         catch { unset vi }
625         while 1 {
626                 if {![regexp -expanded $manyitemre $l dummy \
627                         thiskey thisval rhs]} {
628                     errexpect-error "badly formatted"
629                 }
630                 set vi($thiskey) $thisval
631                 if {![string length $rhs]} break
632                 regsub {^, } $rhs {} rhs
633                 set l "\[$rhs\]"
634         }
635         vessel vi
636     }
637
638     if {[llength $newnotes]} {
639         foreach vid [lsort [array names notes]] {
640             if {![info exists notes_used($vid)]} {
641                 manyset $notes($vid) lno notename
642                 note-info $lno $vid $notename {} \
643                     "vessel in notes no longer found"
644             }
645         }
646     }
647 }
648
649 proc load-clipboard-file {fn} {
650     set f [open $fn]
651     glset clipboard [read $f]
652     close $f
653 }
654
655
656 #---------- loading and parsing the chart ----------
657
658 proc load-chart {} {
659     global chart scraper
660     debug "FETCHING CHART"
661     set chart [eval exec $scraper [list | perl -we {
662         use strict;
663         use CommodsScrape;
664         use IO::File;
665         use IO::Handle;
666         yppedia_chart_parse(\*STDIN, (new IO::File ">/dev/null"),
667                 sub { sprintf "%d %d", @_; },
668                 sub { printf "archlabel %d %d %s\n", @_; },
669                 sub { printf "island %s %s\n", @_; },
670                 sub { printf "league %s %s %s.\n", @_; },
671                 sub { printf STDERR "warning: %s: incomprehensible: %s", @_; }
672                         );
673         STDOUT->error and die $!;
674     }]]
675 }
676
677
678 set scale 16
679
680 proc coord {c} {
681         global scale
682         return [expr {$c * $scale}]
683 }
684
685 proc chart-got/archlabel {args} { }
686 proc chart-got/island {x y args} {
687 #       debug "ISLE $x $y $args"
688         global canvas isleloc
689         set isleloc($args) [list $x $y]
690         set sz 5
691 #       $canvas create oval \
692 #               [expr {[coord $x] - $sz}] [expr {[coord $y] - $sz}] \
693 #               [expr {[coord $x] + $sz}] [expr {[coord $y] + $sz}] \
694 #               -fill blue
695         $canvas create text [coord $x] [coord $y] \
696                 -text $args -anchor s
697 }
698 proc chart-got/league {x1 y1 x2 y2 kind} {
699 #       debug "LEAGUE $x1 $y1 $x2 $y2 $kind"
700         global canvas
701         set l [$canvas create line \
702                 [coord $x1] [coord $y1] \
703                 [coord $x2] [coord $y2]]
704         if {![string compare $kind .]} {
705                 $canvas itemconfigure $l -dash .
706         }
707 }
708
709 proc redraw-needed {} {
710     global redraw_after
711     debug "REDRAW NEEDED"
712     if {[info exists redraw_after]} return
713     set redraw_after [after 250 draw]
714 }
715
716 proc draw {} {
717     global chart found isleloc canvas redraw_after
718
719     catch { after cancel $redraw_after }
720     catch { unset redraw_after }
721     
722     $canvas delete all
723
724     foreach l [split $chart "\n"] {
725 #       debug "CHART-GOT $l"
726         set proc [lindex $l 0]
727         eval chart-got/$proc [lrange $l 1 end]
728     }
729
730     set lastislandname {}
731     foreach key [lsort [array names found]] {
732         set c [llength $found($key)]
733 #       debug "SHOWING $key $c"
734         regexp {^(.*) (\S+)$} $key dummy islandname code
735
736         if {![filters-say-yes $code]} continue
737
738         if {[string compare $lastislandname $islandname]} {
739                 manyset $isleloc($islandname) x y
740                 set x [coord $x]
741                 set y [coord $y]
742                 set lastislandname $islandname
743 #               debug "START Y $y"
744         }
745
746         if {$c > 1} { set qty [format %d $c] } else { set qty {} }
747         code2canvas $code $canvas $x y $qty 2 \
748             [list show-report $islandname $code]
749 #       debug "NEW Y $y"
750     }
751
752     panner::updatecanvas-bbox .cp.ctrl.pan
753 }
754
755
756 #---------- parser error reporting ----------
757
758 proc parser-control-create {w base invokebuttontext etl_title} {
759     frame $w
760     button $w.do -text $invokebuttontext -command invoke_$base
761
762     frame $w.resframe -width 120 -height 32
763     button $w.resframe.res -text {} -anchor nw \
764         -padx 1 -pady 1 -borderwidth 0 -justify left
765     glset deffont_$base [$w.resframe.res cget -font]
766     place $w.resframe.res -relx 0.5 -y 0 -anchor n
767
768     pack $w.do -side top
769     pack $w.resframe -side top -expand y -fill both
770
771     set eb .err_$base
772     toplevel $eb
773     wm withdraw $eb
774     wm title $eb "where-vessels - $etl_title"
775
776     label $eb.title -text $etl_title
777     pack $eb.title -side top
778
779     button $eb.close -text Close -command [list wm withdraw $eb]
780     pack $eb.close -side bottom
781
782     frame $eb.emsg -bd 2 -relief groove
783     label $eb.emsg.lab -text "Error:"
784     text $eb.emsg.text -height 1
785     pack $eb.emsg.text -side bottom
786     pack $eb.emsg.lab -side left
787
788     pack $eb.emsg -side top -pady 2
789
790     frame $eb.text -bd 2 -relief groove
791     pack $eb.text -side bottom -pady 2
792     
793     label $eb.text.lab
794
795     text $eb.text.text -width 85 \
796         -xscrollcommand [list $eb.text.xscroll set] \
797         -yscrollcommand [list $eb.text.yscroll set]
798     $eb.text.text tag configure error \
799         -background red -foreground white
800
801     scrollbar $eb.text.xscroll -orient horizontal \
802         -command [list $eb.text.text xview]
803     scrollbar $eb.text.yscroll -orient vertical \
804         -command [list $eb.text.text yview]
805
806     grid configure $eb.text.lab -row 0 -column 0 -sticky w
807     grid configure $eb.text.text -row 1 -column 0
808     grid configure $eb.text.yscroll -sticky ns -row 1 -column 1
809     grid configure $eb.text.xscroll -sticky ew -row 2 -column 0
810 }
811
812 proc parser-control-ok-core {w base background show} {
813     debug "parser-control-ok-core $w $base $background $show"
814     upvar #0 deffont_$base deffont
815     $w.resframe.res configure \
816         -background $background -disabledforeground black -font $deffont \
817         -state disabled -command {} \
818         -text $show
819 }    
820 proc parser-control-ok {w base show} {
821     parser-control-ok-core $w $base green $show
822 }
823 proc parser-control-none {w base show} {
824     parser-control-ok-core $w $base blue $show
825 }
826 proc parser-control-failed-core {w base foreground background smallfont
827                                  tiny summary fulldesc fulldata} {
828     debug "parser-control-failed-core $w $base $summary $fulldesc"
829     upvar #0 deffont_$base deffont
830     set eb .err_$base
831
832     $eb.emsg.text delete 0.0 end
833     $eb.emsg.text insert end $summary
834
835     $eb.text.lab configure -text $fulldesc
836     $eb.text.text delete 0.0 end
837     $eb.text.text insert end $fulldata
838
839     regsub -all {.{18}} $tiny "&\n" ewrap
840
841     if {$smallfont} {
842         set font fixed
843     } else {
844         set font $deffont
845     }
846
847     $w.resframe.res configure \
848         -background $background -foreground $foreground -font $font \
849         -state normal -command [list wm deiconify $eb] \
850         -text $ewrap
851 }
852     
853 proc parser-control-failed-expected {w base emsg lno ei fulldesc newdata} {
854     set eb .err_$base
855
856     set line [lindex [split $ei "\n"] 0]
857     debug "parser-control-failed-expected: $w $base: $lno: $emsg\n $line"
858
859     parser-control-failed-core $w $base \
860         white red 1 \
861         "err: [string trim $emsg]: \"$line\"" \
862         "at line $lno: $emsg" \
863         $fulldesc $newdata
864
865     $eb.text.text tag add error $lno.0 $lno.end
866     $eb.text.text see $lno.0    
867 }
868 proc parser-control-failed-unexpected {w base emsg ei} {
869     global errorInfo
870     parser-control-failed-core $w $base \
871         black yellow 1 \
872         $emsg $emsg "Details and stack trace:" $ei
873 }
874
875 proc reparse {base varname old fulldesc okshow noneshow parse ok} {
876     upvar #0 $varname var
877     manyset [errexpect-catch {
878         uplevel 1 $parse
879         if {[string length [string trim $var]]} {
880             parser-control-ok .cp.ctrl.$base $base $okshow
881         } else {
882             parser-control-none .cp.ctrl.$base $base $noneshow
883         }
884     }] failed emsg lno ei
885     if {$failed} {
886         parser-control-failed-expected .cp.ctrl.$base $base \
887             $emsg $lno $ei $fulldesc $var
888         set var $old
889         uplevel 1 $parse
890     } else {
891         uplevel 1 $ok
892     }
893 }
894
895 #---------- main user interface ----------
896
897 proc widgets-setup {} {
898     global canvas debug pirate ocean
899
900     wm geometry . 1024x480
901     wm title . "where-vessels - $pirate on the $ocean ocean"
902
903     #----- map -----
904
905     frame .f -border 1 -relief groove
906     set canvas .f.c
907     canvas $canvas
908     pack $canvas -expand 1 -fill both
909     pack .f -expand 1 -fill both -side left
910
911     #----- control panels and filter -----
912
913     frame .cp
914     frame .filter -relief groove -bd 2
915     pack .cp .filter -side top
916
917     label .filter.title -text Filter
918     grid configure .filter.title -row 0 -column 0 -columnspan 2
919
920     #----- control panel -----
921
922     frame .cp.ctrl
923     pack .cp.ctrl -side left -anchor n
924
925     debug "BBOX [$canvas bbox all]"
926
927     panner::canvas-scroll-bbox .f.c
928     panner::create .cp.ctrl.pan .f.c 120 120 $debug
929
930     pack .cp.ctrl.pan -side top -pady 10 -padx 5
931     frame .cp.ctrl.zoom
932     pack .cp.ctrl.zoom -side top
933
934     button .cp.ctrl.zoom.out -text - -font {Courier 16} -command {zoom /2}
935     button .cp.ctrl.zoom.in  -text + -font {Courier 16} -command {zoom *2}
936     pack .cp.ctrl.zoom.out .cp.ctrl.zoom.in -side left
937
938     parser-control-create .cp.ctrl.acquire \
939         acquire Acquire \
940         "Clipboard parsing error" \
941         
942     pack .cp.ctrl.acquire -side top -pady 2
943
944     parser-control-create .cp.ctrl.notes \
945         notes "Reload notes" \
946         "Vessel notes loading report" \
947         
948     pack .cp.ctrl.notes -side top -pady 2
949
950     #----- decoding etc. report -----
951
952     frame .cp.report
953     pack .cp.report -side left -anchor n
954
955     label .cp.report.island -text { }
956
957     canvas .cp.report.abbrev -width 1 -height 15
958
959     frame .cp.report.code
960     label .cp.report.code.lab -text Code:
961     glset report_code { }
962     entry .cp.report.code.code -state readonly \
963         -textvariable report_code -width 15
964     pack .cp.report.code.lab .cp.report.code.code -side left
965     frame .cp.report.details -bd 2 -relief groove -padx 2 -pady 2
966
967     listbox .cp.report.list -height 5
968
969     pack .cp.report.island .cp.report.abbrev .cp.report.details \
970         .cp.report.list .cp.report.code -side top
971     pack configure .cp.report.details -fill x
972
973     foreach sw {inport class subclass lock own xabbrev} {
974         label .cp.report.details.$sw -text { }
975         pack .cp.report.details.$sw -side top -anchor w
976     }
977 }
978
979 proc report-set {sw val} { .cp.report.details.$sw configure -text $val }
980
981 proc show-report {islandname code} {
982     .cp.report.island configure -text $islandname
983
984     .cp.report.abbrev delete all
985     set y 2
986     code2canvas $code .cp.report.abbrev 5 y {} 0 {}
987     manyset [.cp.report.abbrev bbox all] minx dummy maxx dummy
988     .cp.report.abbrev configure -width [expr {$maxx-$minx+4}]
989
990     glset report_code $code
991     show-report-decode $code
992
993     set kk "$islandname $code"
994     upvar #0 found($kk) k
995
996     .cp.report.list delete 0 end
997
998     foreach entry $k {
999         manyset $entry vid name
1000         .cp.report.list insert end $name
1001     }
1002 }
1003
1004 proc zoom {extail} {
1005     global scale canvas
1006     set nscale [expr "\$scale $extail"]
1007     debug "ZOOM $scale $nscale"
1008     if {$nscale < 1 || $nscale > 200} return
1009     set scale $nscale
1010     draw
1011 }
1012
1013 proc invoke_acquire {} {
1014     global clipboard errorInfo
1015     set old $clipboard
1016
1017     if {[catch {
1018         set clipboard [clipboard get]
1019     } emsg]} {
1020         parser-control-failed-unexpected .cp.ctrl.acquire acquire \
1021             $emsg "fetching clipboard:\n\n$errorInfo"
1022         return
1023     }
1024
1025     reparse acquire \
1026         clipboard $old "Clipboard contents:" { acquired ok } { no vessels } {
1027             parse-clipboard
1028         } {
1029             display-note-infos
1030         }
1031     draw
1032 }
1033
1034 proc invoke_notes {} {
1035     global notes_data errorInfo notes_loc
1036     set old $notes_data
1037     
1038     if {[catch {
1039         load-notes
1040     } emsg]} {
1041         parser-control-failed-unexpected .cp.ctrl.notes notes \
1042             $emsg "loading $notes_loc:\n\n$errorInfo"
1043         return
1044     }
1045
1046     reparse notes \
1047         notes_data $old "Vessel notes:" "loaded ok" { no notes } {
1048             parse-notes
1049             parse-clipboard
1050         } {
1051             display-note-infos
1052         }
1053     draw
1054 }
1055
1056 #---------- main program ----------
1057
1058 vesselclasses-init
1059
1060 parseargs
1061 argdefaults
1062 httpclientsetup where-vessels
1063 load-chart
1064 widgets-setup
1065 make-filters
1066
1067 set notes_data {}
1068 if {[catch { parse-clipboard } emsg]} {
1069     puts stderr "$emsg\n$errorInfo"
1070     exit 1
1071 }
1072 after idle invoke_notes
1073
1074 draw