chiark / gitweb /
Normalise commodity name case (from uploads)
[ypp-sc-tools.db-live.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 {}
105 set scraper {./yppedia-ocean-scraper --chart}
106 set info_cache _vessel-info-cache
107 set info_source rsync.yarrg.chiark.net::yarrg/vessel-info
108 set filter_lockown_separate 0
109
110 proc parseargs {} {
111     global ai argv
112     global debug scraper
113     set ai 0
114
115     while {[regexp {^\-} [set arg [lindex $argv $ai]]]} {
116         incr ai
117         switch -exact -- $arg {
118             -- { break }
119             --pirate { glset pirate [string totitle [nextarg]] }
120             --ocean { glset ocean [string totitle [nextarg]] }
121             --clipboard-file { load-clipboard-file [nextarg] }
122             --local-html-dir { lappend scraper --local-html-dir=[nextarg] }
123             --notes { glset notes_loc [nextarg] }
124             --vessel-info-source { glset info_source [nextarg] }
125             --filter-separate-lock-owner { glset filter_lockown_separate 1 }
126             --debug { incr debug }
127             default { badusage "bad option $arg; see README.where-vessels" }
128         }
129     }
130     set argv [lrange $argv $ai end]
131     if {[llength $argv]} { badusage "non-option args not allowed" }
132 }
133
134 proc have-notes {} {
135     global notes_loc
136     return [string length $notes_loc]
137 }
138 proc have-ownership {} {
139     global pirate
140     return [expr {[have-notes] && [string length $pirate]}]
141 }
142
143 proc argdefaults {} {
144     global ocean notes_loc pirate scraper
145     if {![info exists ocean] ||
146         (![info exists pirate] && [string length $notes_loc])} {
147         set cmd {./yarrg --find-window-only --quiet}
148         if {[info exists ocean]} { lappend cmd --ocean $ocean }
149         if {[info exists pirate]} { lappend cmd --pirate $pirate }
150         if {[catch {
151             manyset [split [eval exec $cmd] " "] ocean pirate
152         } emsg]} {
153             puts stderr "yarrg: [string trim $emsg]"
154             puts stderr "Alternatively pass, --ocean and perhaps --pirate options to where-vessels"
155             exit 1
156         }
157         if {![llength $ocean] || ![llength $pirate]} {
158             error "$ocean $pirate ?"
159         }
160     }
161     if {![info exists pirate]} {
162         set pirate {}
163     }
164     if {![have-notes]} {
165         glset filter_lockown_separate 1
166     }
167
168     lappend scraper $ocean
169 }
170
171
172 #---------- loading and parsing the vessel notes ----------
173
174 proc load-notes {} {
175     global notes_loc notes_data
176     if {[regexp {^\w+\:} $notes_loc]} {
177         update
178         debug "FETCHING NOTES $notes_loc"
179         set req [::http::geturl $notes_loc]
180         switch -glob [::http::status $req].[::http::ncode $req] {
181             ok.200 { }
182             ok.* { error "retrieving vessel-notes: [::http::code $req]" }
183             * { error "Retrieving vessel-notes: [::http::error $req]" }
184         }
185         set newdata [::http::data $req]
186         ::http::cleanup $req
187     } else {
188         debug "READING NOTES $notes_loc"
189         set vn [open $notes_loc]
190         set newdata [read $vn]
191         close $vn
192     }
193     set notes_data $newdata
194 }
195
196 proc parse-notes {} {
197     global notes_data notes
198     catch { unset notes }
199
200     set lno 0
201     foreach l [split $notes_data "\n"] {
202         incr lno
203         errexpect-setline $lno $l
204         set l [string trim $l]
205         if {![string length $l]} continue
206         if {[regexp {^\#} $l]} continue
207         if {![regexp -expanded \
208                   {^ (\d+) (?: \s+([^=]*?) )? \s* =
209                       (?: \s* (\S+)
210                        (?: \s+ (\S+) )?)? $} \
211                   $l dummy vid vname owner note]} {
212               errexpect-error "badly formatted"
213         }
214         set vname [string trim $vname]
215         if {[info exists notes($vid)]} {
216             errexpect-error "duplicate vesselid $vid"
217         }
218         set notes($vid) [list $lno $vname $owner $note]
219     }
220 }
221
222 proc note-info {lno vid name island description} {
223     global note_infos
224     lappend note_infos [list $lno $vid $name $island $description]
225 }
226
227 proc display-note-infos {} {
228     global note_infos note_missings notes
229
230     set nmissing [llength $note_missings]
231     debug "display-note-infos $nmissing [array size notes]"
232
233     if {[llength $note_infos]} {
234         set tiny "[llength $note_infos] warning(s)"
235     } elseif {$nmissing && [array size notes]} {
236         set tiny "$nmissing missing"
237     } else {
238         return
239     }
240
241     set infodata {}
242
243     foreach info $note_infos {
244         manyset $info lno vid name island description
245         append infodata "vessel"
246         append infodata " $vid"
247         if {[string length $name]} { append infodata " $name" }
248         if {[string length $island]} { append infodata " ($island)" }
249         append infodata ": " $description "\n"
250     }
251
252     if {$nmissing} {
253         if {[string length $infodata]} { append infodata "\n" }
254         append infodata "$nmissing vessel(s) not mentioned in notes:\n"
255         set last_island {}
256         foreach info [lsort $note_missings] {
257             manyset $info island name vid
258             if {[string compare $island $last_island]} {
259                 append infodata "# $island:\n"
260                 set last_island $island
261             }
262             append infodata [format "%-9d %-29s =\n" $vid $name]
263         }
264     }
265
266     parser-control-failed-core .cp.ctrl.notes notes \
267         white blue 0 \
268         $tiny \
269         "[llength $note_infos] warning(s);\
270          $nmissing vessel(s) missing" \
271         "Full description of warnings and missing vessels:" \
272         $infodata
273 }
274
275 #---------- vessel info and icons ----------
276
277 proc info-cache-update {} {
278     global info_source info_cache
279     file mkdir $info_cache
280     exec sh -c "cp -u icons/* $info_cache/."
281
282     if {[string length $info_source]} {
283         set cmdl [list \
284                   rsync -udLKtOzm \
285                   --exclude=*~ --exclude=*.bak --exclude=.* --exclude=*.tmp \
286                   $info_source/ $info_cache 2>@ stderr]
287         debug "INFO-CACHE $cmdl"
288         eval exec $cmdl
289     }
290
291     set f [open $info_cache/vessel-info]
292     glset vessel_size_data [read $f]
293     close $f
294 }
295
296 proc vesselinfo-init {} {
297     global vc_game2code vc_code2abbrev vc_code2full vc_codes
298
299     global vessel_size_data
300     manyset $vessel_size_data sizeinfos subclassinfos
301
302     set vc_codes {}
303     foreach {game code abbrev full} $sizeinfos {
304         if {![regexp {^[a-z][a-z]$} $code code]} { error "bad code" }
305         if {![regexp {^[a-z][a-z]$} $abbrev abbrev]} { error "bad abbrev" }
306         lappend vc_codes $code
307         set vc_game2code($game) $code
308         set vc_code2abbrev($code) $abbrev
309         set vc_code2full($code) $full
310         load-icon $abbrev
311     }
312
313     global vsc_code2report
314     global vsc_game2code
315     set vsc_game2code(null) {}
316     set vsc_code2report() Ordinary
317     set vsc_code2report(!) "(Special/L.E.)"
318     foreach {game code full} $subclassinfos {
319         if {![regexp {^[A-Z]$} $code code]} { error "bad code" }
320         set vsc_game2code($game) $code
321         set vsc_code2report($code) $full
322     }
323
324     load-icon atsea
325     set owners {ours dot query}
326     foreach b $owners { load-icon $b }
327     foreach a {battle borrow dot} {
328         load-icon $a
329         foreach b $owners { load-icon-combine $a $b }
330     }
331 }
332
333 proc load-icon {icon} {
334     global info_cache
335     image create bitmap icon/$icon -file $info_cache/$icon.xbm
336 }
337
338 proc load-icon-combine {args} {
339     global info_cache
340     set cmd {}
341     set delim "pnmcat -lr "
342     foreach icon $args {
343         append cmd $delim " <(xbmtopbm $info_cache/$icon.xbm)"
344         set delim " <(pbmmake -white 1 1)"
345     }
346     append cmd " | pbmtoxbm"
347     debug "load-icon-combine $cmd"
348     image create bitmap icon/[join $args +] -data [exec bash -c $cmd]
349 }
350
351 #---------- vessel properties ----------
352
353 proc code-lockown2icon {lockown} {
354     manyset [split $lockown ""] lock notown
355     set l "
356          [lindex {battle borrow dot} $lock]
357          [lindex {ours dot query {} {} dot} $notown]
358     "
359     if {[llength $l]} { return icon/[join $l +] } { return {} }
360 }
361
362 proc canvas-horiz-stack {xvar xoff y bind type args} {
363     upvar 1 $xvar x
364     upvar 1 canvas canvas
365     set id [eval $canvas create $type [expr {$x+$xoff}] $y $args]
366     set bbox [$canvas bbox $id]
367 #   debug "CANVAS-HORIZ-STACK $type $x $xoff $id $bbox [list $args]"
368     set x [lindex $bbox 2]
369     $canvas bind $id <ButtonPress> $bind
370     return $id
371 }
372
373 proc code2canvas1 {code canvas} {
374     set y 2
375     code2canvas $code $canvas 5 y {} 0 {}
376     manyset [$canvas bbox all] minx dummy maxx dummy
377     $canvas configure -width [expr {$maxx-$minx+4}]
378 }
379
380 proc code2canvas {code canvas x yvar qty qtylen bind} {
381     global vc_code2abbrev
382     upvar 1 $yvar y
383
384     manyset [split $code _] inport size subclass lockown xabbrev
385
386     set stackx $x
387     incr stackx 2
388     set imy [expr {$y+2}]
389
390     if {!$inport} { incr qtylen -1 }
391     if {$qtylen<=0} { set qtylen {} }
392     set qty [format "%${qtylen}s" $qty]
393
394     set qtyid [canvas-horiz-stack stackx 0 $y $bind \
395                    text -anchor nw -font fixed -text $qty]
396
397     if {!$inport} {
398         canvas-horiz-stack stackx 0 $imy $bind \
399             image -anchor nw -image icon/atsea
400         incr stackx
401     }
402     
403     upvar #0 vc_code2abbrev($size) vcabb
404     if {![info exists vcabb]} {
405         set vcabb vc-$size
406         image create bitmap icon/$vcabb -data \
407             [exec pbmtext -builtin fixed $size | pnminvert | pnmcrop >t.pnm]
408     }
409     canvas-horiz-stack stackx -1 $imy $bind \
410             image -anchor nw -image icon/$vcabb
411
412     if {[string length $subclass]} {
413         canvas-horiz-stack stackx 0 $y $bind \
414             text -anchor nw -font fixed -text \
415             $subclass
416     }
417
418     incr stackx
419     set lockownicon [code-lockown2icon $lockown]
420     if {[string length $lockownicon]} {
421         canvas-horiz-stack stackx 0 $imy $bind \
422             image -anchor nw -image $lockownicon
423         incr stackx
424     }
425     
426     if {[string length $xabbrev]} {
427         canvas-horiz-stack stackx 0 $y $bind \
428             text -anchor nw -font fixed -text \
429             $xabbrev
430     }
431     
432     set bbox [$canvas bbox $qtyid]
433     set ny [lindex $bbox 3]
434     set bid [$canvas create rectangle \
435                  $x $y $stackx $ny \
436                  -fill white]
437
438     set y $ny
439     $canvas lower $bid $qtyid
440
441     $canvas bind $bid <ButtonPress> $bind
442 }
443
444 proc show-report-decode {code} {
445     global vc_code2full
446
447     smash-prepare
448
449     manyset [split $code _] inport sizecode subclass lockown xabbrev
450     manyset [split $lockown ""] lock notown
451     
452     report-set inport [lindex {{At Sea} {In port}} $inport]
453
454     upvar #0 vc_code2full($sizecode) sizefull
455     upvar #0 smash_sizeinexact($sizecode) sizeinexact
456     set size_report $sizefull
457     if {[info exists sizeinexact]} { set size_report "($sizefull+)" }
458     report-set size $size_report
459
460     global smash_subclass
461     if {$smash_subclass >= 2} {
462         report-set subclass "(Any class)"
463     } elseif {[
464                upvar #0 vsc_code2report($subclass) subclass_report
465                info exists subclass_report
466               ]} {
467         report-set subclass $subclass_report
468     } else {
469         report-set subclass "Class \"$subclass\""
470     }
471
472     report-set lock [lindex {
473         {Battle ready} {Unlocked} {Locked}
474         {(All lock states)} {(Not battle ready)}
475     } $lock]
476
477     if {[have-notes]} {
478         switch -exact $notown {
479             0 { report-set own "Yours" }
480             1 { report-set own "Other pirate's" }
481             2 { report-set own "Owner unknown" }
482             3 { report-set own "(All ownerships)" }
483             4 - 5 { report-set own "(Not yours / unknown)" }
484             default { report-set own "?? $notown" }
485         }
486     }
487
488     global smash_xabbrev_map
489     if {![have-notes]} {
490     } elseif {[llength $smash_xabbrev_map]} {
491         if {[string length $xabbrev]} {
492             report-set xabbrev "(Flags: $xabbrev)"
493         } else {
494             report-set xabbrev "(No flags)"
495         }
496     } else {
497         if {[string length $xabbrev]} {
498             report-set xabbrev "Notes flags: $xabbrev"
499         } else {
500             report-set xabbrev "No flags in notes"
501         }
502     }
503 }
504
505 #---------- common to smashing and filtering ----------
506
507 proc make-control {parent ctrl label ekind} {
508     debug "MAKE-CONTROL [list $parent $ctrl $label $ekind]"
509     label $parent.lab_$ctrl -text $label -justify left
510     $ekind $parent.$ctrl
511     manyset [grid size $parent] dummy row
512     incr row
513     grid configure $parent.lab_$ctrl -row $row -column 0 -sticky nw -pady 4
514     grid configure $parent.$ctrl -row $row -column 1 -sticky w -pady 3
515     return $parent.$ctrl
516 }
517
518 proc begin-control-grid {cw count rows inrow} {
519     if {!$inrow} { set inrow [expr {($count + $rows) / $rows}] }
520     upvar #0 control_grid_properties($cw) props
521     set props [list $rows $inrow]
522     return $cw
523 }
524
525 proc make-control-grid-elem {cw kind ix ekind args} {
526     upvar #0 control_grid_properties($cw) props
527     manyset $props rows inrow
528
529     set ew $cw.$ix
530
531     debug "MAKE-CONTROL-GRID-ELEM $cw $kind $ix $ekind $rows $inrow $ew"
532
533     eval [list $ekind $ew] $args
534
535     switch -exact $kind {
536         ix {
537             grid configure $ew -sticky sw \
538                 -row [expr {$ix / $inrow}] \
539                 -column [expr {$ix % $inrow}]
540         }
541         final {
542             grid configure $ew -sticky se \
543                 -row [expr {$rows-1}] \
544                 -column [expr {$inrow-1}]
545         }
546         default {
547             error "$kind ?"
548         }
549     }
550     return $ew
551 }
552
553 proc control-tickbox-flip {varsvn values onflip} {
554     upvar #0 $varsvn vars
555     foreach val $values {
556         set vars($val) [expr {!$vars($val)}]
557     }
558     $onflip c.-tickbox-flip $varsvn $values
559 }
560
561 proc populate-control-grid-tickboxes {cw rows inrow varsvn values flipvalues
562                             label_kind valvn default_get label_get onflip} {
563     debug "POPULATE-CONTROL-GRID-TICKBOXES $cw $rows $inrow $varsvn\
564              [list $values] $label_kind $valvn"
565
566     upvar #0 $varsvn vars
567     upvar 1 $valvn val
568     set count [llength $values]
569
570     begin-control-grid $cw $count $rows $inrow
571
572     for {set ix 0} {$ix < $count} {incr ix} {
573         set val [lindex $values $ix]
574         set vars($val) [uplevel 1 $default_get]
575         set ew [make-control-grid-elem $cw ix $ix checkbutton \
576                     -variable ${varsvn}($val) \
577                     -font fixed \
578                     -command [list $onflip c.-g.-tickbox $cw $val]]
579         $ew configure -$label_kind [uplevel 1 $label_get]
580         switch -exact $label_kind {
581             image { $ew configure -height 16 }
582         }
583     }
584     [make-control-grid-elem $cw final invert button] \
585         configure \
586         -text flip -padx 0 -pady 0 \
587         -command [list control-tickbox-flip $varsvn $flipvalues $onflip]
588 }
589
590 #---------- smashing ----------
591
592 proc smash-code {code} {
593     manyset [split $code _] inport size subclass lockown xabbrev
594
595     upvar #0 smash_sizemap($size) smsize
596
597     global smash_subclass
598     if {$smash_subclass > 1} {
599         set subclass {}
600     } elseif {$smash_subclass && [string length $subclass]} {
601         set subclass !
602     }
603
604     global smash_owner
605     switch $smash_owner {
606         0 { }
607         1 { regsub {[12]$} $lockown 5 lockown }
608         2 {
609             if {[regexp {^0.} $lockown]} {
610                 # battle ready / all lock states
611                 set lockown 03
612             } elseif {[regexp {^.0} $lockown]} {
613                 # not battle ready / yours
614                 set lockown 40
615             } else {
616                 # state (not battle ready) / not known to be yours
617                 regsub {.$} $lockown 4 lockown
618             }
619         }
620         3 { regsub {.$} $lockown {3} lockown }
621         4 { set lockown 33 }
622     }
623
624     global smash_xabbrev_map
625     set xabbrev [string map $smash_xabbrev_map $xabbrev]
626
627     return [join [list $inport $smsize $subclass $lockown $xabbrev] _]
628 }
629
630 proc smash-prepare {} {
631     global vc_codes smash_sizemap smash_size smash_sizeinexact
632     set mapto {}
633     catch { unset smash_sizeinexact }
634     foreach size $vc_codes {
635         if {!$smash_size($size)} {
636             set mapto $size
637         } else {
638             set smash_sizeinexact($mapto) 1
639         }
640         set smash_sizemap($size) $mapto
641     }
642
643     global smash_xabbrev_a smash_xabbrev_b smash_xabbrev_map
644     set smash_xabbrev_map {}
645     foreach a [split $smash_xabbrev_a ""] b [split $smash_xabbrev_b ""] {
646         if {![string length $a]} continue
647         lappend smash_xabbrev_map $a $b
648     }
649     debug "SMASH-PREPAE xabbrev_map=[list $smash_xabbrev_map]"
650 }
651
652 proc make-smasher {sma label ekind} {
653     return [make-control .smash $sma $label $ekind]
654 }
655
656 proc make-radio-smasher {sma label variable descs rows inrow} {
657     set w [make-smasher $sma $label frame]
658     begin-control-grid $w [llength $descs] $rows $inrow
659     for {set i 0} {$i < [llength $descs]} {incr i} {
660         make-control-grid-elem $w ix $i \
661             radiobutton \
662             -variable $variable -value $i \
663             -command [list redraw-needed radio-smasher $sma] \
664             -text [lindex $descs $i]
665     }
666     return $w
667 }
668
669 proc make-smashers {} {
670     global vc_codes vc_code2abbrev
671     set cw [make-smasher size "Size\n round\n down" frame]
672     populate-control-grid-tickboxes $cw 2 0 smash_size \
673         $vc_codes [lrange $vc_codes 1 end] \
674         image val { expr 0 } { expr {"icon/$vc_code2abbrev($val)"} } \
675         redraw-needed
676     $cw.0 configure -state disabled
677
678     glset smash_subclass 0
679     make-radio-smasher subclass Class smash_subclass \
680         {Show Normal/LE Hide} 1 0
681
682     glset smash_owner [expr {[have-ownership] ? 0 : 3}]
683     set cw [make-radio-smasher owner "Lock/\nowner" smash_owner \
684                 {Show Yours? {For you} Lock Hide} 2 3]
685     if {![have-notes]} { $cw.0 configure -state disabled }
686     if {![have-ownership]} {
687         foreach ix {1 2} { $cw.$ix configure -state disabled }
688     }
689
690     set cw [make-smasher xabbrev "Flags" frame]
691     foreach ix {1 3} ab {a b} width {14 12} {
692         set vn smash_xabbrev_$ab
693         global $vn
694         set $vn {}
695         entry $cw.$ix -textvariable $vn -width $width
696         trace add variable $vn write [list redraw-needed $vn]
697     }
698     set ix 0
699     foreach str {y/ / /d} { label $cw.$ix -text $str; incr ix 2 }
700     eval pack [lsort [winfo children $cw]] -side left
701 }
702
703 #---------- filtering ----------
704
705 set filters {}
706
707 proc filter-values/size {} { global vc_codes; return $vc_codes }
708 proc filter-icon/size {code} {
709     upvar #0 vc_code2abbrev($code) abb
710     return icon/$abb
711 }
712 proc filter-default/size {code} { return 1 }
713 proc filter-says-yes/size {codel} {
714     set sizecode [lindex $codel 1]
715     upvar #0 filter_size($sizecode) yes
716     return $yes
717 }
718
719 proc filter-values/lock {} { return {0 1 2} }
720 proc filter-icon/lock {lock} { return [code-lockown2icon ${lock}3] }
721 proc filter-default/lock {lock} { return 1 }
722 proc filter-says-yes/lock {codel} {
723     regexp {^.} [lindex $codel 3] lock
724     upvar #0 filter_lock($lock) yes
725     debug "FILTER-SAYS-YES/LOCK $codel $lock $yes"
726     return $yes
727 }
728
729 proc filter-values/own {} { return {0 1 2} }
730 proc filter-icon/own {own} { return [code-lockown2icon 3${own}] }
731 proc filter-default/own {own} { return 1 }
732 proc filter-says-yes/own {codel} {
733     regexp {.$} [lindex $codel 3] own
734     upvar #0 filter_own($own) yes
735     debug "FILTER-SAYS-YES/OWN $codel $own $yes"
736     return $yes
737 }
738
739 proc filter-values/lockown {} {
740     foreach lv {0 1 2} {
741         foreach ov {0 1 2} {
742             lappend vals "$lv$ov"
743         }
744     }
745     return $vals
746 }
747 proc filter-icon/lockown {lockown} { return [code-lockown2icon $lockown] }
748 proc filter-default/lockown {lockown} {
749     return [regexp {^[01]|^2[^1]} $lockown]
750 }
751 proc filter-says-yes/lockown {codel} {
752     set lockown [lindex $codel 3]
753     upvar #0 filter_lockown($lockown) yes
754     debug "FILTER-SAYS-YES/LOCKOWN $codel $lockown $yes"
755     return $yes
756 }
757
758 proc filter-validate/xabbre {re} {
759     if {[catch {
760         regexp -- $re {}
761     } emsg]} {
762         regsub {^.*:\s*} $emsg {} emsg
763         regsub {^.*(.{30})$} $emsg {\1} emsg
764         return $emsg
765     }
766     return {}
767 }
768 proc filter-says-yes/xabbre {codel} {
769     global filter_xabbre
770     set xabbrev [lindex $codel 4]
771     return [regexp -- $filter_xabbre $xabbrev]
772 }
773
774 proc make-tickbox-filter {fil label rows inrow} {
775     set values [filter-values/$fil]
776
777     if {![catch { info args filter-icon/$fil }]} {
778         set label_get { filter-icon/$fil $val }
779         set label_kind image
780     } else {
781         set label_get { filter-map/$fil $val }
782         set label_kind text
783     }
784
785     set fw [make-filter $fil $label frame]
786
787     populate-control-grid-tickboxes $fw $rows $inrow filter_$fil \
788         $values $values \
789         $label_kind val { filter-default/$fil $val } $label_get \
790         specific-filter-adjusted
791 }
792
793 proc entry-filter-changed {fw fil n1 n2 op} {
794     global errorInfo
795     upvar #0 filter_$fil realvar
796     upvar #0 filterentered_$fil entryvar
797     global def_background
798     debug "entry-filter-changed $fw $fil $entryvar"
799     if {[catch {
800         set error [filter-validate/$fil $entryvar]
801         if {[string length $error]} {
802             $fw.error configure -text $error -foreground white -background red
803         } else {
804             $fw.error configure -text { } -background $def_background
805             set realvar $entryvar
806             specific-filter-adjusted entry-filter-changed $fw
807         }
808     } emsg]} {
809         puts stderr "FILTER CHECK ERROR $emsg $errorInfo"
810     }
811 }
812
813 proc make-entry-filter {fil label def} {
814     global filterentered_$fil
815     upvar #0 filter_$fil realvar
816     set realvar $def
817     set fw [make-filter $fil $label frame]
818     entry $fw.entry -textvariable filterentered_$fil
819     label $fw.error
820     glset def_background [$fw.error cget -background]
821     trace add variable filterentered_$fil write \
822         [list entry-filter-changed $fw $fil]
823     pack $fw.entry $fw.error -side top -anchor w
824 }
825
826 proc make-filter {fil label ekind} {
827     global filters
828     lappend filters $fil
829     return [make-control .filter $fil $label $ekind]
830 }
831
832 proc make-filters {} {
833     global filter_lockown_separate
834     make-tickbox-filter size Size 2 0
835     if {!$filter_lockown_separate} {
836         make-tickbox-filter lockown "Lock/\nowner" 2 6
837     } else {
838         make-tickbox-filter lock "Lock" 1 0
839         if {[have-notes]} {
840             make-tickbox-filter own "Owner" 1 0
841         }
842     }
843     make-entry-filter xabbre "Flags\n regexp" {}
844 }
845
846 proc specific-filter-adjusted {args} {
847     glset filterstyle 3
848     eval redraw-needed $args
849 }
850
851 proc filterstyle-changed {n1 n2 op} {
852     global filterstyle
853     debug "FILTERSTYLE-CHANGED $filterstyle"
854     redraw-needed filterstyle-changed
855 }
856
857 proc filters-say-yes {code} {
858     global filters filterstyle
859     set codel [split $code _]
860     set lockown [lindex $codel 3]
861     switch -exact $filterstyle {
862         0 { return 1 }
863         1 { return [filter-default/lockown $lockown] }
864         2 { return [regexp {^.0} $lockown] }
865         3 { }
866         default { error $filterstyle }
867     }
868     
869     foreach fil $filters {
870         if {![filter-says-yes/$fil $codel]} {
871             debug "FILTERS-SAY-YES $code NO $fil"
872             return 0
873         }
874     }
875     debug "FILTERS-SAY-YES $code YES $filters"
876     return 1
877 }
878     
879 #---------- loading and parsing the clipboard (vessel locations) ----------
880
881 proc vessel {vin} {
882     global pirate notes_used note_missings newnotes
883     upvar 1 $vin vi
884
885     set codel {}
886     lappend codel [errexpect-arrayget-boolean vi inPort]
887
888     set gamesize [errexpect-arrayget vi vesselClass]
889     upvar #0 vc_game2code($gamesize) size
890     if {![info exists size]} {
891         set size "($gamesize)"
892         upvar #0 vc_code2abbrev($size) vcabb
893         set vcabb vc-$size
894         set data [exec pbmtext -builtin fixed " $gamesize " \
895                  | pnminvert | pnmcrop | pbmtoxbm]
896         debug "INVENTED ICON $vcabb $data"
897         image create bitmap icon/$vcabb -data $data
898             
899         global vc_code2full
900         set vc_code2full($size) "Type \"$gamesize\""
901     }
902     lappend codel $size
903
904     set gamesubclass [errexpect-arrayget vi vesselSubclass]
905     upvar #0 vsc_game2code($gamesubclass) subclass
906     if {[info exists subclass]} {
907         lappend codel $subclass
908     } else {
909         lappend codel ($gamesubclass)
910     }
911
912     switch -exact [errexpect-arrayget vi isLocked]/[ \
913                    errexpect-arrayget vi isBattleReady] {
914         true/false      { set lock 2 }
915         false/false     { set lock 1 }
916         false/true      { set lock 0 }
917         default         { errexpect-error "unexpected isLocked/isBattleReady" }
918     }
919
920     set vid [errexpect-arrayget vi vesselId]
921     upvar #0 notes($vid) note
922     set realname [errexpect-arrayget vi vesselName]
923     set island [errexpect-arrayget vi islandName]
924
925     set owner {}
926     set xabbrev {}
927     if {[info exists note]} {
928         manyset $note lno notename owner xabbrev
929         if {[string compare -nocase $realname $notename]} {
930             note-info $lno $vid $realname $island \
931                 "notes say name is $notename"
932         }
933         if {[string length $owner]} {
934             if {![string compare $owner $pirate]} {
935                 set notown 0
936             } else {
937                 set notown 1
938             }
939         } else {
940             set notown 2
941         }
942         append abbrev $xabbrev
943         set notes_used($vid) 1
944
945     } else {
946         set notown 2
947         lappend note_missings [list $island $realname $vid]
948     }
949
950     lappend codel "$lock$notown" $xabbrev
951     lappend newnotes [list $vid $realname $owner $xabbrev]
952     set kk "$island [join $codel _]"
953     upvar #0 found($kk) k
954     lappend k [list $vid $realname $owner]
955  
956     debug "CODED $kk $vid $realname"
957 }
958
959 set clipboard {}
960 proc parse-clipboard {} {
961     global clipboard found notes notes_used newnotes
962
963     catch { unset found }
964     catch { unset notes_used }
965     glset note_infos {}
966     glset note_missings {}
967
968     set newnotes {}
969     
970     set itemre { (\w+) = ([^=]*) }
971     set manyitemre "^\\\[ $itemre ( (?: ,\\ $itemre)* ) \\]\$"
972     debug $manyitemre
973
974     set lno 0
975     foreach l [split $clipboard "\n"] {
976         incr lno
977         errexpect-setline $lno $l
978         if {![string length $l]} continue
979         catch { unset vi }
980         while 1 {
981                 if {![regexp -expanded $manyitemre $l dummy \
982                         thiskey thisval rhs]} {
983                     errexpect-error "badly formatted"
984                 }
985                 set vi($thiskey) $thisval
986                 if {![string length $rhs]} break
987                 regsub {^, } $rhs {} rhs
988                 set l "\[$rhs\]"
989         }
990         vessel vi
991     }
992
993     if {[llength $newnotes]} {
994         foreach vid [lsort [array names notes]] {
995             if {![info exists notes_used($vid)]} {
996                 manyset $notes($vid) lno notename
997                 note-info $lno $vid $notename {} \
998                     "vessel in notes no longer found"
999             }
1000         }
1001     }
1002 }
1003
1004 proc load-clipboard-file {fn} {
1005     set f [open $fn]
1006     glset clipboard [read $f]
1007     close $f
1008 }
1009
1010
1011 #---------- loading and parsing the chart ----------
1012
1013 proc load-chart {} {
1014     global chart scraper
1015     debug "FETCHING CHART"
1016     set chart [eval exec $scraper [list | perl -we {
1017         use strict;
1018         use CommodsScrape;
1019         use IO::File;
1020         use IO::Handle;
1021         yppedia_chart_parse(\*STDIN, (new IO::File ">/dev/null"),
1022                 sub { sprintf "%d %d", @_; },
1023                 sub { printf "archlabel %d %d %s\n", @_; },
1024                 sub { printf "island %s {%s} %s\n", @_; },
1025                 sub { printf "league %s %s %s.\n", @_; },
1026                 sub { printf STDERR "warning: %s: incomprehensible: %s", @_; }
1027                         );
1028         STDOUT->error and die $!;
1029     }]]
1030 }
1031
1032 proc init-scales {} {
1033     global scales scaleix scale
1034     set defscale 16
1035     set scales {1 2 3 4 5 6 8}
1036     set e12 {10 12 15 18 22 27 33 39 47 56 68 82}
1037     foreach t $e12 {
1038         if {$t < $defscale} { set scaleix [llength $scales] }
1039         lappend scales $t
1040     }
1041     foreach t [lrange $e12 0 6] { lappend scales [expr {$t * 10}] }
1042     set scale [lindex $scales $scaleix]
1043 }
1044
1045 proc coord {c} {
1046         global scale
1047         return [expr {$c * $scale}]
1048 }
1049
1050 proc chart-got/archlabel {args} { }
1051 proc chart-got/island {x y isle sizecol} {
1052         debug "ISLE $x $y $isle $sizecol"
1053         global canvas isleloc
1054         set isleloc($isle) [list $x $y]
1055         set sz 5
1056 #       $canvas create oval \
1057 #               [expr {[coord $x] - $sz}] [expr {[coord $y] - $sz}] \
1058 #               [expr {[coord $x] + $sz}] [expr {[coord $y] + $sz}] \
1059 #               -fill blue
1060         set colour "#888"
1061         if {[string match *_col $sizecol]} { set colour black }
1062         $canvas create text [coord $x] [coord $y] \
1063                 -text $isle -anchor s -fill $colour
1064 }
1065 proc chart-got/league {x1 y1 x2 y2 kind} {
1066 #       debug "LEAGUE $x1 $y1 $x2 $y2 $kind"
1067         global canvas
1068         set l [$canvas create line \
1069                 [coord $x1] [coord $y1] \
1070                 [coord $x2] [coord $y2]]
1071         if {![string compare $kind .]} {
1072                 $canvas itemconfigure $l -dash .
1073         }
1074 }
1075
1076 proc debug-filter-array {array} {
1077     upvar #0 $array a
1078     set m " FILTER $array"
1079     foreach k [lsort [array names a]] {
1080         append m " $k=$a($k)"
1081     }
1082     debug $m
1083 }
1084
1085 proc redraw-needed {args} {
1086     global redraw_after
1087     debug "REDRAW NEEDED $args"
1088     if {[info exists redraw_after]} return
1089
1090     global filterstyle
1091     debug " FILTER style $filterstyle"
1092     debug-filter-array filter_size
1093     debug-filter-array filter_lockown
1094     global filter_xabbre
1095     debug " FILTER xabbre $filter_xabbre"
1096
1097     set redraw_after [after 250 draw]
1098 }
1099
1100 proc draw {} {
1101     global chart found isleloc canvas redraw_after islandnames smfound
1102
1103     catch { after cancel $redraw_after }
1104     catch { unset redraw_after }
1105     
1106     $canvas delete all
1107
1108     foreach l [split $chart "\n"] {
1109 #       debug "CHART-GOT $l"
1110         set proc [lindex $l 0]
1111         eval chart-got/$proc [lrange $l 1 end]
1112     }
1113
1114     smash-prepare
1115
1116     catch { unset smfound }
1117     foreach key [lsort [array names found]] {
1118         regexp {^(.*) (\S+)$} $key dummy islandname code
1119
1120         if {![filters-say-yes $code]} continue
1121
1122         set smcode [smash-code $code]
1123         debug "smashed $code => $smcode"
1124         set smkey "$islandname $smcode"
1125         foreach vessel $found($key) {
1126             lappend smfound($smkey) [list $vessel $code]
1127         }
1128     }
1129
1130     set islandnames {}
1131     set lastislandname {}
1132     foreach smkey [lsort [array names smfound]] {
1133         set c [llength $smfound($smkey)]
1134         regexp {^(.*) (\S+)$} $smkey dummy islandname code
1135         debug "SHOWING [list $smkey $c $islandname $code l=$lastislandname]"
1136
1137         if {[string compare $lastislandname $islandname]} {
1138                 manyset $isleloc($islandname) x y
1139                 set x [coord $x]
1140                 set y [coord $y]
1141                 set lastislandname $islandname
1142                 lappend islandnames $islandname
1143 #               debug "START Y $y"
1144         }
1145
1146         if {$c > 1} { set qty [format %d $c] } else { set qty {} }
1147         code2canvas $code $canvas $x y $qty 2 \
1148             [list show-report $islandname $code]
1149 #       debug "NEW Y $y"
1150     }
1151
1152     panner::updatecanvas-bbox .cp.ctrl.pan
1153
1154     islandnames-update
1155 }
1156
1157
1158 #---------- info toplevel ----------
1159
1160 proc info-toplevel-create {info title} {
1161     toplevel $info
1162     wm withdraw $info
1163     wm title $info "where-vessels - $title"
1164     wm protocol $info WM_DELETE_WINDOW [list wm withdraw $info]
1165
1166     button $info.close -text Close -command [list wm withdraw $info]
1167     pack $info.close -side bottom
1168 }
1169
1170 #---------- parser error reporting ----------
1171
1172 proc parser-control-create {w base invokebuttontext etl_title} {
1173     frame $w
1174     button $w.do -text $invokebuttontext -command invoke_$base -pady 3
1175
1176     frame $w.resframe -width 120 -height 32
1177     button $w.resframe.res -text {} -anchor nw \
1178         -padx 1 -pady 1 -borderwidth 0 -justify left
1179     glset deffont_$base [$w.resframe.res cget -font]
1180     place $w.resframe.res -relx 0.5 -y 0 -anchor n
1181
1182     pack $w.do -side top
1183     pack $w.resframe -side top -expand y -fill both
1184
1185     set eb .err_$base
1186     info-toplevel-create $eb $etl_title
1187
1188     label $eb.title -text $etl_title
1189     pack $eb.title -side top
1190
1191     frame $eb.emsg -bd 2 -relief groove
1192     label $eb.emsg.lab -anchor nw -text "Error:"
1193     text $eb.emsg.text -height 1
1194     pack $eb.emsg.text -side bottom -fill x
1195     pack $eb.emsg.lab -side left
1196
1197     pack $eb.emsg -side top -pady 2 -fill x
1198
1199     frame $eb.text -bd 2 -relief groove
1200     pack $eb.text -side bottom -pady 2 -fill both -expand y
1201     
1202     label $eb.text.lab -anchor nw
1203
1204     text $eb.text.text -width 85 \
1205         -xscrollcommand [list $eb.text.xscroll set] \
1206         -yscrollcommand [list $eb.text.yscroll set]
1207     $eb.text.text tag configure error \
1208         -background red -foreground white
1209
1210     scrollbar $eb.text.xscroll -orient horizontal \
1211         -command [list $eb.text.text xview]
1212     scrollbar $eb.text.yscroll -orient vertical \
1213         -command [list $eb.text.text yview]
1214
1215     grid configure $eb.text.lab -row 0 -column 0 -sticky w -columnspan 2
1216     grid configure $eb.text.text -row 1 -column 0 -sticky news
1217     grid configure $eb.text.yscroll -sticky ns -row 1 -column 1
1218     grid configure $eb.text.xscroll -sticky ew -row 2 -column 0
1219     grid rowconfigure $eb.text 0 -weight 0
1220     grid rowconfigure $eb.text 1 -weight 1
1221     grid rowconfigure $eb.text 2 -weight 0
1222     grid columnconfigure $eb.text 0 -weight 1
1223     grid columnconfigure $eb.text 1 -weight 0
1224 }
1225
1226 proc parser-control-ok-core {w base background show} {
1227     debug "parser-control-ok-core $w $base $background $show"
1228     upvar #0 deffont_$base deffont
1229     $w.resframe.res configure \
1230         -background $background -disabledforeground black -font $deffont \
1231         -state disabled -command {} \
1232         -text $show
1233 }    
1234 proc parser-control-ok {w base show} {
1235     parser-control-ok-core $w $base green $show
1236 }
1237 proc parser-control-none {w base show} {
1238     parser-control-ok-core $w $base blue $show
1239 }
1240 proc parser-control-failed-core {w base foreground background smallfont
1241                                  tiny summary fulldesc fulldata} {
1242     debug "parser-control-failed-core $w $base $summary $fulldesc"
1243     upvar #0 deffont_$base deffont
1244     set eb .err_$base
1245
1246     $eb.emsg.text delete 0.0 end
1247     $eb.emsg.text insert end $summary
1248
1249     $eb.text.lab configure -text $fulldesc
1250     $eb.text.text delete 0.0 end
1251     $eb.text.text insert end $fulldata
1252
1253     regsub -all {.{18}} $tiny "&\n" ewrap
1254
1255     if {$smallfont} {
1256         set font fixed
1257     } else {
1258         set font $deffont
1259     }
1260
1261     $w.resframe.res configure \
1262         -background $background -foreground $foreground -font $font \
1263         -state normal -command [list wm deiconify $eb] \
1264         -text $ewrap
1265 }
1266     
1267 proc parser-control-failed-expected {w base emsg lno ei fulldesc newdata} {
1268     set eb .err_$base
1269
1270     set line [lindex [split $ei "\n"] 0]
1271     debug "parser-control-failed-expected: $w $base: $lno: $emsg\n $line"
1272
1273     parser-control-failed-core $w $base \
1274         white red 1 \
1275         "err: [string trim $emsg]: \"$line\"" \
1276         "at line $lno: $emsg" \
1277         $fulldesc $newdata
1278
1279     $eb.text.text tag add error $lno.0 $lno.end
1280     $eb.text.text see $lno.0    
1281 }
1282 proc parser-control-failed-unexpected {w base emsg ei} {
1283     global errorInfo
1284     parser-control-failed-core $w $base \
1285         black yellow 1 \
1286         $emsg $emsg "Details and stack trace:" $ei
1287 }
1288
1289 proc reparse {base varname old fulldesc okshow noneshow parse ok} {
1290     upvar #0 $varname var
1291     manyset [errexpect-catch {
1292         uplevel 1 $parse
1293         if {[string length [string trim $var]]} {
1294             parser-control-ok .cp.ctrl.$base $base $okshow
1295         } else {
1296             parser-control-none .cp.ctrl.$base $base $noneshow
1297         }
1298     }] failed emsg lno ei
1299     if {$failed} {
1300         parser-control-failed-expected .cp.ctrl.$base $base \
1301             $emsg $lno $ei $fulldesc $var
1302         set var $old
1303         uplevel 1 $parse
1304     } else {
1305         uplevel 1 $ok
1306     }
1307 }
1308
1309 #---------- island names selection etc. ----------
1310
1311 proc islandnames-update {} {
1312     global islandnames
1313     .islands.count configure -text [format "ships at %d island(s)" \
1314                                         [llength $islandnames]]
1315 }
1316
1317 proc islandnames-select {} {
1318     .islands.clip configure -relief sunken -state disabled
1319     selection own -command islandnames-deselect .islands.clip
1320 }
1321 proc islandnames-deselect {} {
1322     .islands.clip configure -relief raised -state normal
1323 }
1324
1325 proc islandnames-handler {offset maxchars} {
1326     global islandnames
1327     return [string range [join $islandnames ", "] \
1328                 $offset [expr {$offset+$maxchars-1}]]
1329 }
1330
1331 #---------- print to postscript ----------
1332
1333 proc print-to-postscript {} {
1334     global canvas ocean
1335     set postscript_fontmap(fixed) {Courier 12}
1336     manyset [$canvas bbox all] xmin ymin xmax ymax
1337     set file where-vessels.$ocean.ps
1338     $canvas postscript -file $file -rotate 1 \
1339         -width [expr {$xmax-$xmin}] \
1340         -height [expr {$ymax-$ymin}] \
1341         -fontmap postscript_fontmap
1342     .printed.info configure -text "Printed to $file
1343
1344 Usually, the next thing would be something like"
1345     set text "epsffit 0 0 595.276 841.89 <$file >t.ps"
1346     .printed.rune configure -state normal
1347     .printed.rune delete 1.0 end
1348     .printed.rune insert end $text
1349     .printed.rune configure -width [string length $text] -state disabled
1350     update idletasks
1351     wm deiconify .printed
1352 }
1353
1354 #---------- main user interface ----------
1355
1356 proc widgets-setup {} {
1357     global canvas debug pirate ocean filterstyle
1358
1359     wm geometry . 1200x800
1360     if {[string length $pirate]} {
1361         wm title . "where-vessels - $pirate on the $ocean ocean"
1362     } else {
1363         wm title . "where-vessels - $ocean ocean"
1364     }
1365
1366     #----- map -----
1367
1368     frame .f -border 1 -relief groove
1369     set canvas .f.c
1370     canvas $canvas
1371     pack $canvas -expand 1 -fill both
1372     pack .f -expand 1 -fill both -side left
1373
1374     #----- control panels and filter -----
1375
1376     frame .cp
1377     frame .smash -relief groove -bd 2 -padx 1
1378     frame .filter -relief groove -bd 2 -padx 1
1379     frame .islands -pady 2
1380     pack .cp .filter .islands .smash -side top -fill x
1381
1382     label .smash.title -text {Display/combine details}
1383     grid .smash.title -row 0 -column 0 -columnspan 2
1384
1385     set filterstyle [expr {[have-ownership] ? 1 : 3}]
1386     trace add variable filterstyle write filterstyle-changed
1387
1388     frame .filter.title
1389     label .filter.title.title -text Show
1390     pack .filter.title.title -side left
1391     foreach fing {0 1 2 3} {
1392         radiobutton .filter.title.f$fing \
1393             -variable filterstyle -value $fing \
1394             -text [lindex {All Useable Mine These:} $fing]
1395         pack .filter.title.f$fing -side left
1396     }
1397     if {![have-ownership]} {
1398         foreach fing {1 2} { .filter.title.f$fing configure -state disabled }
1399     }
1400
1401     grid configure .filter.title -row 0 -column 0 -columnspan 2
1402
1403     #----- control panel -----
1404
1405     frame .cp.ctrl
1406     pack .cp.ctrl -side left -anchor n
1407
1408     debug "BBOX [$canvas bbox all]"
1409
1410     panner::canvas-scroll-bbox .f.c
1411     panner::create .cp.ctrl.pan .f.c 120 120 $debug
1412
1413     pack .cp.ctrl.pan -side top -pady 0 -padx 5
1414     frame .cp.ctrl.zoom
1415     pack .cp.ctrl.zoom -side top
1416
1417     foreach inout {out in} minplus {- +} {
1418         button .cp.ctrl.zoom.$inout -text $minplus -font {Courier 16} \
1419             -command "zoom ${minplus}1" -pady 0
1420         pack .cp.ctrl.zoom.$inout -side left
1421     }
1422
1423     parser-control-create .cp.ctrl.acquire \
1424         acquire Acquire \
1425         "Clipboard parsing error" \
1426         
1427     pack .cp.ctrl.acquire -side top -pady 2
1428
1429     parser-control-create .cp.ctrl.notes \
1430         notes "Reload notes" \
1431         "Vessel notes loading report" \
1432
1433     pack .cp.ctrl.notes -side top -pady 2
1434
1435     if {![have-notes]} {
1436         .cp.ctrl.notes.do configure -state disabled
1437     }
1438
1439     button .cp.ctrl.print -text {Print to file} -command print-to-postscript
1440     pack .cp.ctrl.print -side top
1441         
1442     #----- message saying we've printed -----
1443
1444     info-toplevel-create .printed "printed"
1445
1446     label .printed.info
1447     text .printed.rune -state disabled -height 1 -borderwidth 0
1448     pack .printed.info -side top
1449     pack .printed.rune -side top
1450
1451     #----- island name count and copy -----
1452
1453     label .islands.count
1454     button .islands.clip -text "copy island names" -pady 2 -padx 2 \
1455          -command islandnames-select
1456     selection handle .islands.clip islandnames-handler
1457     pack .islands.count .islands.clip -side left
1458
1459     #----- decoding etc. report -----
1460
1461     frame .cp.report
1462     pack .cp.report -side left -anchor n -fill both -expand y
1463
1464     label .cp.report.island -text { }
1465
1466     canvas .cp.report.abbrev -width 1 -height 15
1467
1468     frame .cp.report.code
1469     label .cp.report.code.lab -text Code:
1470     glset report_code { }
1471     entry .cp.report.code.code -state readonly \
1472         -textvariable report_code -width 15
1473     pack .cp.report.code.lab .cp.report.code.code -side left
1474     frame .cp.report.details -bd 2 -relief groove -padx 2 -pady 2
1475
1476     listbox .cp.report.list -height 5
1477
1478     canvas .cp.report.abbrev1 -width 1 -height 15
1479
1480     pack .cp.report.island .cp.report.abbrev .cp.report.details \
1481         .cp.report.list .cp.report.abbrev1 -side top
1482     bind .cp.report.list <<ListboxSelect>> show-report-abbrev1
1483
1484     pack configure .cp.report.details -fill x
1485     pack configure .cp.report.list -fill x
1486
1487     foreach sw {inport size subclass lock own xabbrev} {
1488         label .cp.report.details.$sw -text { }
1489         pack .cp.report.details.$sw -side top -anchor w
1490     }
1491 }
1492
1493 proc report-set {sw val} { .cp.report.details.$sw configure -text $val }
1494
1495 proc show-report {islandname code} {
1496     .cp.report.island configure -text $islandname
1497
1498     .cp.report.abbrev delete all
1499     code2canvas1 $code .cp.report.abbrev
1500
1501     glset report_code $code
1502     show-report-decode $code
1503
1504     set kk "$islandname $code"
1505     upvar #0 smfound($kk) vessels
1506
1507     global report_list_codes
1508     set report_list_codes {}
1509     .cp.report.list delete 0 end
1510
1511     foreach foundelem $vessels {
1512         manyset $foundelem elem code
1513         manyset $elem vid name owner
1514         lappend owned($owner) [list $name $code]
1515     }
1516
1517     foreach owner [lsort [array names owned]] {
1518         if {[string length $owner]} {
1519             set owndesc "$owner's"
1520         } else {
1521             set owndesc "Owner unknown"
1522         }
1523         if {[have-notes]} {
1524             .cp.report.list insert end "$owndesc:"
1525             lappend report_list_codes {}
1526         }
1527         foreach ownelem $owned($owner) {
1528             manyset $ownelem name code
1529             .cp.report.list insert end " $name"
1530             lappend report_list_codes $code
1531         }
1532     }
1533     show-report-abbrev1
1534 }
1535
1536 proc show-report-abbrev1 {} {
1537     global report_list_codes
1538     .cp.report.abbrev1 delete all
1539     set ix [.cp.report.list curselection]
1540     debug "SHOW-REPORT-ABBREV1 $ix $report_list_codes"
1541     if {[llength $ix] != 1} return
1542     set code [lindex $report_list_codes $ix]
1543     if {![string length $code]} return
1544     if {![have-notes]} {
1545         manyset [split $code _] inport size subclass lockown xabbrev
1546         regsub {.$} $lockown 3 lockown
1547         set code [join [list $inport $size $subclass $lockown $xabbrev] _]
1548     }
1549     code2canvas1 $code .cp.report.abbrev1
1550 }
1551
1552 proc zoom {amt} {
1553     global scaleix scales scale canvas
1554     incr scaleix $amt
1555     if {$scaleix < 0} { set scaleix 0 }
1556     set nscales [llength $scales]
1557     if {$scaleix >= $nscales} { set scaleix [expr {$nscales-1}] }
1558     set scale [lindex $scales $scaleix]
1559     debug "ZOOM $amt $scaleix $scale"
1560     draw
1561 }
1562
1563 proc invoke_acquire {} {
1564     global clipboard errorInfo
1565     set old $clipboard
1566
1567     if {[catch {
1568         set clipboard [clipboard get]
1569     } emsg]} {
1570         parser-control-failed-unexpected .cp.ctrl.acquire acquire \
1571             $emsg "fetching clipboard:\n\n$errorInfo"
1572         return
1573     }
1574
1575     reparse acquire \
1576         clipboard $old "Clipboard contents:" { acquired ok } { no vessels } {
1577             parse-clipboard
1578         } {
1579             display-note-infos
1580         }
1581     draw
1582 }
1583
1584 proc invoke_notes {} {
1585     global notes_data errorInfo notes_loc
1586     set old $notes_data
1587     
1588     if {[catch {
1589         load-notes
1590     } emsg]} {
1591         parser-control-failed-unexpected .cp.ctrl.notes notes \
1592             $emsg "loading $notes_loc:\n\n$errorInfo"
1593         return
1594     }
1595
1596     reparse notes \
1597         notes_data $old "Vessel notes:" "loaded ok" { no notes } {
1598             parse-notes
1599             parse-clipboard
1600         } {
1601             display-note-infos
1602         }
1603     draw
1604 }
1605
1606 #---------- main program ----------
1607
1608 init-scales
1609 parseargs
1610 argdefaults
1611 httpclientsetup where-vessels
1612 info-cache-update
1613 vesselinfo-init
1614 load-chart
1615 widgets-setup
1616 make-filters
1617 make-smashers
1618
1619 set notes_data {}
1620 if {[catch { parse-clipboard } emsg]} {
1621     puts stderr "$emsg\n$errorInfo"
1622     exit 1
1623 }
1624 if {[have-notes]} {
1625     after idle invoke_notes
1626 }
1627
1628 draw
1629
1630 if {$debug} {
1631     package require Tclx
1632     commandloop -async \
1633         -prompt1 { return "where-vessels% " } \
1634         -prompt2 { return "> " }
1635 }
1636
1637 # some runes I use:
1638 #
1639 # offline development
1640 #   ./where-vessels --notes ~/vessel-notes --vessel-info-source '' --pirate Aristarchus --ocean Midnight --debug --local-html-dir . --clipboard-file ~/clipboard-aristarchus
1641 #
1642 # updating published vessel info
1643 #   rsync -r --exclude=\*~ yarrg/icons/. ijackson@chiark.greenend.org.uk:/home/ftp/users/ijackson/yarrg/vessel-info/.