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