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