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