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