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