chiark / gitweb /
a558c42a2e068c316c1fbed96552ae6d8bb60169
[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 vessel-notes
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
109 proc parseargs {} {
110     global ai argv
111     global debug scraper
112     set ai 0
113
114     while {[regexp {^\-} [set arg [lindex $argv $ai]]]} {
115         incr ai
116         switch -exact -- $arg {
117             -- { break }
118             --pirate { glset pirate [string totitle [nextarg]] }
119             --ocean { glset ocean [string totitle [nextarg]] }
120             --clipboard-file { load-clipboard-file [nextarg] }
121             --local-html-dir { lappend scraper --local-html-dir=[nextarg] }
122             --notes { glset notes_loc [nextarg] }
123             --vessel-info-source { glset info_source [nextarg] }
124             --debug { incr debug }
125             default { badusage "unknown option $arg" }
126         }
127     }
128     set argv [lrange $argv $ai end]
129     if {[llength $argv]} { badusage "non-option args not allowed" }
130 }
131
132 proc argdefaults {} {
133     global ocean notes_loc pirate scraper
134     if {![info exists ocean] || ![info exists pirate]} {
135         set cmd {./yarrg --find-window-only --quiet}
136         if {[info exists ocean]} { lappend cmd --ocean $ocean }
137         if {[info exists pirate]} { lappend cmd --pirate $pirate }
138         manyset [split [eval exec $cmd] " "] ocean pirate
139         if {![llength $ocean] || ![llength $pirate]} {
140             error "$ocean $pirate ?"
141         }
142     }
143     lappend scraper $ocean
144 }
145
146
147 #---------- loading and parsing the vessel notes ----------
148
149 proc load-notes {} {
150     global notes_loc notes_data
151     if {[regexp {^\w+\:} $notes_loc]} {
152         update
153         debug "FETCHING NOTES $notes_loc"
154         set req [::http::geturl $notes_loc]
155         switch -glob [::http::status $req].[::http::ncode $req] {
156             ok.200 { }
157             ok.* { error "retrieving vessel-notes: [::http::code $req]" }
158             * { error "Retrieving vessel-notes: [::http::error $req]" }
159         }
160         set newdata [::http::data $req]
161         ::http::cleanup $req
162     } else {
163         debug "READING NOTES $notes_loc"
164         set vn [open $notes_loc]
165         set newdata [read $vn]
166         close $vn
167     }
168     set notes_data $newdata
169 }
170
171 proc parse-notes {} {
172     global notes_data notes
173     catch { unset notes }
174
175     set lno 0
176     foreach l [split $notes_data "\n"] {
177         incr lno
178         errexpect-setline $lno $l
179         set l [string trim $l]
180         if {![string length $l]} continue
181         if {[regexp {^\#} $l]} continue
182         if {![regexp -expanded \
183                   {^ (\d+) (?: \s+([^=]*?) )? \s* =
184                       (?: \s* (\S+)
185                        (?: \s+ (\S+) )?)? $} \
186                   $l dummy vid vname owner note]} {
187               errexpect-error "badly formatted"
188         }
189         set vname [string trim $vname]
190         if {[info exists notes($vid)]} {
191             errexpect-error "duplicate vesselid $vid"
192         }
193         set notes($vid) [list $lno $vname $owner $note]
194     }
195 }
196
197 proc note-info {lno vid name island description} {
198     global note_infos
199     lappend note_infos [list $lno $vid $name $island $description]
200 }
201
202 proc display-note-infos {} {
203     global note_infos note_missings notes
204
205     set nmissing [llength $note_missings]
206     debug "display-note-infos $nmissing [array size notes]"
207
208     if {[llength $note_infos]} {
209         set tiny "[llength $note_infos] warning(s)"
210     } elseif {$nmissing && [array size notes]} {
211         set tiny "$nmissing missing"
212     } else {
213         return
214     }
215
216     set infodata {}
217
218     foreach info $note_infos {
219         manyset $info lno vid name island description
220         append infodata "vessel"
221         append infodata " $vid"
222         if {[string length $name]} { append infodata " $name" }
223         if {[string length $island]} { append infodata " ($island)" }
224         append infodata ": " $description "\n"
225     }
226
227     if {$nmissing} {
228         if {[string length $infodata]} { append infodata "\n" }
229         append infodata "$nmissing vessel(s) not mentioned in notes:\n"
230         set last_island {}
231         foreach info [lsort $note_missings] {
232             manyset $info island name vid
233             if {[string compare $island $last_island]} {
234                 append infodata "# $island:\n"
235                 set last_island $island
236             }
237             append infodata [format "%-9d %-29s =\n" $vid $name]
238         }
239     }
240
241     parser-control-failed-core .cp.ctrl.notes notes \
242         white blue 0 \
243         $tiny \
244         "[llength $note_infos] warning(s);\
245          $nmissing vessel(s) missing" \
246         "Full description of warnings and missing vessels:" \
247         $infodata
248 }
249
250 #---------- vessel properties ----------
251
252 proc info-cache-update {} {
253     global info_source info_cache
254     file mkdir $info_cache
255     exec sh -c "cp -u icons/* $info_cache/."
256
257     if {[string length $info_source]} {
258         set cmdl [list \
259                   rsync -udLKtOzm \
260                   --exclude=*~ --exclude=*.bak --exclude=.* --exclude=*.tmp \
261                   $info_source/ $info_cache 2>@ stderr]
262         debug "INFO-CACHE $cmdl"
263         eval exec $cmdl
264     }
265
266     set f [open $info_cache/vessel-info]
267     glset vessel_class_data [read $f]
268     close $f
269 }
270
271 proc vesselclasses-init {} {
272     global vc_game2code vc_code2abbrev vc_code2full vc_codes
273
274     global vessel_class_data
275     manyset $vessel_class_data classinfos subclassinfos
276
277     set vc_codes {}
278     foreach {game code abbrev full} $classinfos {
279         if {![regexp {^[a-z][a-z]$} $code code]} { error "bad code" }
280         if {![regexp {^[a-z][a-z]$} $abbrev abbrev]} { error "bad abbrev" }
281         lappend vc_codes $code
282         set vc_game2code($game) $code
283         set vc_code2abbrev($code) $abbrev
284         set vc_code2full($code) $full
285         load-icon $abbrev
286     }
287
288     global vsc_code2report
289     global vsc_game2code
290     set vsc_game2code(null) {}
291     set vsc_code2report() Ordinary
292     set vsc_code2report(!) "Special/L.E."
293     foreach {game code full} $subclassinfos {
294         if {![regexp {^[A-Z]$} $code code]} { error "bad code" }
295         set vsc_game2code($game) $code
296         set vsc_code2report($code) $full
297     }
298
299     load-icon atsea
300     foreach a {battle borrow dot} {
301         foreach b {ours dot query} {
302             load-icon-combine $a $b
303         }
304     }
305 }
306
307 proc load-icon {icon} {
308     global info_cache
309     image create bitmap icon/$icon -file $info_cache/$icon.xbm
310 }
311
312 proc load-icon-combine {args} {
313     global info_cache
314     set cmd {}
315     set delim "pnmcat -lr "
316     foreach icon $args {
317         append cmd $delim " <(xbmtopbm $info_cache/$icon.xbm)"
318         set delim " <(pbmmake -white 1 1)"
319     }
320     append cmd " | pbmtoxbm"
321     debug "load-icon-combine $cmd"
322     image create bitmap icon/[join $args +] -data [exec bash -c $cmd]
323 }
324
325 proc code-lockown2icon {lockown} {
326     manyset [split $lockown ""] lock notown
327     return icon/[
328                  lindex {battle borrow dot} $lock
329                 ]+[
330                    lindex {ours dot query} $notown
331                   ]
332 }
333
334 proc canvas-horiz-stack {xvar xoff y bind type args} {
335     upvar 1 $xvar x
336     upvar 1 canvas canvas
337     set id [eval $canvas create $type [expr {$x+$xoff}] $y $args]
338     set bbox [$canvas bbox $id]
339     set x [lindex $bbox 2]
340     $canvas bind $id <ButtonPress> $bind
341     return $id
342 }
343
344 proc code2canvas {code canvas x yvar qty qtylen bind} {
345     global vc_code2abbrev
346     upvar 1 $yvar y
347
348     manyset [split $code _] inport class subclass lockown xabbrev
349
350     set stackx $x
351     incr stackx 2
352     set imy [expr {$y+2}]
353
354     if {!$inport} { incr qtylen -1 }
355     if {$qtylen<=0} { set qtylen {} }
356     set qty [format "%${qtylen}s" $qty]
357
358     set qtyid [canvas-horiz-stack stackx 0 $y $bind \
359                    text -anchor nw -font fixed -text $qty]
360
361     if {!$inport} {
362         canvas-horiz-stack stackx 0 $imy $bind \
363             image -anchor nw -image icon/atsea
364         incr stackx
365     }
366     
367     upvar #0 vc_code2abbrev($class) vcabb
368     if {![info exists vcabb]} {
369         set vcabb vc-$class
370         image create bitmap icon/$vcabb -data \
371             [exec pbmtext -builtin fixed $class | pnminvert | pnmcrop >t.pnm]
372     }
373     canvas-horiz-stack stackx -1 $imy $bind \
374             image -anchor nw -image icon/$vcabb
375
376     if {[string length $subclass]} {
377         canvas-horiz-stack stackx 0 $y $bind \
378             text -anchor nw -font fixed -text \
379             $subclass
380     }
381
382     incr stackx
383     canvas-horiz-stack stackx 0 $imy $bind \
384         image -anchor nw -image [code-lockown2icon $lockown]
385     incr stackx
386     
387     if {[string length $xabbrev]} {
388         canvas-horiz-stack stackx 0 $y $bind \
389             text -anchor nw -font fixed -text \
390             $xabbrev
391     }
392     
393     set bbox [$canvas bbox $qtyid]
394     set ny [lindex $bbox 3]
395     set bid [$canvas create rectangle \
396                  $x $y $stackx $ny \
397                  -fill white]
398
399     set y $ny
400     $canvas lower $bid $qtyid
401
402     $canvas bind $bid <ButtonPress> $bind
403 }
404
405 proc show-report-decode {code} {
406     global vc_code2full
407
408     manyset [split $code _] inport classcode subclass lockown xabbrev
409     manyset [split $lockown ""] lock notown
410     
411     report-set inport [lindex {{At Sea} {In port}} $inport]
412     report-set class $vc_code2full($classcode)
413
414     upvar #0 vsc_code2report($subclass) subclass_report
415     if {[info exists subclass_report]} {
416         report-set subclass $subclass_report
417     } else {
418         report-set subclass "Subclass \"$subclass\""
419     }
420
421     report-set lock [lindex {
422         {Battle ready} {Unlocked} {Locked}
423     } $lock]
424
425     switch -exact $notown {
426         0 { report-set own "Yours" }
427         1 { report-set own "Other pirate's" }
428         2 { report-set own "Owner unknown" }
429         default { report-set own "?? $notown" }
430     }
431
432     if {[string length $xabbrev]} {
433         report-set xabbrev "Notes flags: $xabbrev"
434     } else {
435         report-set xabbrev "No flags in notes"
436     }
437 }
438
439 #---------- smashing ----------
440
441 set smash_subclass 0
442
443 proc smash-code {code} {
444     manyset [split $code _] inport class subclass lockown xabbrev
445
446     global smash_subclass
447     if {$smash_subclass && [string length $subclass]} {
448         set subclass !
449     }
450
451     return [join [list $inport $class $subclass $lockown $xabbrev] _]
452 }
453
454 #---------- filtering ----------
455
456 set filters {}
457
458 proc filter-values/size {} { global vc_codes; return $vc_codes }
459 proc filter-icon/size {code} {
460     upvar #0 vc_code2abbrev($code) abb
461     return icon/$abb
462 }
463 proc filter-default/size {code} { return 1 }
464 proc filter-says-yes/size {codel} {
465     set sizecode [lindex $codel 1]
466     upvar #0 filter_size($sizecode) yes
467     return $yes
468 }
469
470 proc filter-values/lockown {} {
471     foreach lv {0 1 2} {
472         foreach ov {0 1 2} {
473             lappend vals "$lv$ov"
474         }
475     }
476     return $vals
477 }
478 proc filter-icon/lockown {lockown} { return [code-lockown2icon $lockown] }
479 proc filter-default/lockown {lockown} {
480     return [regexp {^[01]|^2[^1]} $lockown]
481 }
482 proc filter-says-yes/lockown {codel} {
483     set lockown [lindex $codel 3]
484     upvar #0 filter_lockown($lockown) yes
485     return $yes
486 }
487
488 proc filter-validate/xabbre {re} {
489     if {[catch {
490         regexp -- $re {}
491     } emsg]} {
492         regsub {^.*:\s*} $emsg {} emsg
493         regsub {^.*(.{30})$} $emsg {\1} emsg
494         return $emsg
495     }
496     return {}
497 }
498 proc filter-says-yes/xabbre {codel} {
499     global filter_xabbre
500     set xabbrev [lindex $codel 4]
501     return [regexp -- $filter_xabbre $xabbrev]
502 }
503
504 proc filter-tickbox-flip {fil} {
505     upvar #0 filter_$fil vars
506     set values [filter-values/$fil]
507     foreach val $values {
508         set vars($val) [expr {!$vars($val)}]
509     }
510     redraw-needed
511 }
512
513 proc make-tickbox-filter {fil label rows inrow} {
514     upvar #0 filter_$fil vars
515     set fw [make-filter tickbox $fil $label frame]
516     set values [filter-values/$fil]
517     set nvalues [llength $values]
518     if {!$inrow} {
519         set inrow [expr {($nvalues + $rows) / $rows}]
520     }
521     set noicons [catch { info args filter-icon/$fil }]
522     for {set ix 0} {$ix < $nvalues} {incr ix} {
523         set val [lindex $values $ix]
524         set vars($val) [filter-default/$fil $val]
525         checkbutton $fw.$ix -variable filter_${fil}($val) \
526             -font fixed -command redraw-needed
527         if {!$noicons} {
528             $fw.$ix configure -image [filter-icon/$fil $val] -height 16
529         } else {
530             $fw.$ix configure -text [filter-map/$fil $val]
531         }
532         grid configure $fw.$ix -sticky sw \
533             -row [expr {$ix / $inrow}] \
534             -column [expr {$ix % $inrow}]
535     }
536     button $fw.invert -text flip -command [list filter-tickbox-flip $fil] \
537         -padx 0 -pady 0
538     grid configure $fw.invert -sticky se \
539         -row [expr {$rows-1}] \
540         -column [expr {$inrow-1}]
541 }
542
543 proc entry-filter-changed {fw fil n1 n2 op} {
544     global errorInfo
545     upvar #0 filter_$fil realvar
546     upvar #0 filterentered_$fil entryvar
547     global def_background
548     debug "entry-filter-changed $fw $fil $entryvar"
549     if {[catch {
550         set error [filter-validate/$fil $entryvar]
551         if {[string length $error]} {
552             $fw.error configure -text $error -foreground white -background red
553         } else {
554             $fw.error configure -text { } -background $def_background
555             set realvar $entryvar
556             redraw-needed
557         }
558     } emsg]} {
559         puts stderr "FILTER CHECK ERROR $emsg $errorInfo"
560     }
561 }
562
563 proc make-entry-filter {fil label def} {
564     global filterentered_$fil
565     upvar #0 filter_$fil realvar
566     set realvar $def
567     set fw [make-filter entry $fil $label frame]
568     entry $fw.entry -textvariable filterentered_$fil
569     label $fw.error
570     glset def_background [$fw.error cget -background]
571     trace add variable filterentered_$fil write \
572         [list entry-filter-changed $fw $fil]
573     pack $fw.entry $fw.error -side top -anchor w
574 }
575
576 proc make-filter {kind fil label ekind} {
577     global filters
578     label .filter.lab_$fil -text $label -justify left
579     $ekind .filter.$fil
580     lappend filters $fil
581     set nfilters [llength $filters]
582     grid configure .filter.lab_$fil -row $nfilters -column 0 -sticky nw -pady 4
583     grid configure .filter.$fil -row $nfilters -column 1 -sticky w -pady 3
584     return .filter.$fil
585 }
586
587 proc make-filters {} {
588     make-tickbox-filter size Size 2 0
589     make-tickbox-filter lockown "Lock/\nowner" 2 6
590     make-entry-filter xabbre "Flags\n regexp" {}
591 }
592
593 proc filterstyle-changed {n1 n2 op} {
594     global filterstyle
595     debug "filterstyle-changed $filterstyle"
596     redraw-needed
597 }
598
599 proc filters-say-yes {code} {
600     global filters filterstyle
601     debug "filters-say-yes $code"
602     set codel [split $code _]
603     set lockown [lindex $codel 3]
604     switch -exact $filterstyle {
605         0 { return 1 }
606         1 { return [filter-default/lockown $lockown] }
607         2 { return [regexp {^.0} $lockown] }
608         3 { }
609         default { error $filterstyle }
610     }
611     
612     foreach fil $filters {
613         if {![filter-says-yes/$fil $codel]} { return 0 }
614     }
615     return 1
616 }
617     
618 #---------- loading and parsing the clipboard (vessel locations) ----------
619
620 proc vessel {vin} {
621     global pirate notes_used note_missings newnotes
622     upvar 1 $vin vi
623
624     set codel {}
625     lappend codel [errexpect-arrayget-boolean vi inPort]
626
627     set gameclass [errexpect-arrayget vi vesselClass]
628     upvar #0 vc_game2code($gameclass) class
629     if {![info exists class]} {
630         set class "($gameclass)"
631         upvar #0 vc_code2abbrev($class) vcabb
632         set vcabb vc-$class
633         set data [exec pbmtext -builtin fixed " $gameclass " \
634                  | pnminvert | pnmcrop | pbmtoxbm]
635         debug "INVENTED ICON $vcabb $data"
636         image create bitmap icon/$vcabb -data $data
637             
638         global vc_code2full
639         set vc_code2full($class) "Type \"$gameclass\""
640     }
641     lappend codel $class
642
643     set gamesubclass [errexpect-arrayget vi vesselSubclass]
644     upvar #0 vsc_game2code($gamesubclass) subclass
645     if {[info exists subclass]} {
646         lappend codel $subclass
647     } else {
648         lappend codel ($gamesubclass)
649     }
650
651     switch -exact [errexpect-arrayget vi isLocked]/[ \
652                    errexpect-arrayget vi isBattleReady] {
653         true/false      { set lock 2 }
654         false/false     { set lock 1 }
655         false/true      { set lock 0 }
656         default         { errexpect-error "unexpected isLocked/isBattleReady" }
657     }
658
659     set vid [errexpect-arrayget vi vesselId]
660     upvar #0 notes($vid) note
661     set realname [errexpect-arrayget vi vesselName]
662     set island [errexpect-arrayget vi islandName]
663
664     set owner {}
665     set xabbrev {}
666     if {[info exists note]} {
667         manyset $note lno notename owner xabbrev
668         if {[string compare -nocase $realname $notename]} {
669             note-info $lno $vid $realname $island \
670                 "notes say name is $notename"
671         }
672         if {[string length $owner]} {
673             if {![string compare $owner $pirate]} {
674                 set notown 0
675             } else {
676                 set notown 1
677             }
678         } else {
679             set notown 2
680         }
681         append abbrev $xabbrev
682         set notes_used($vid) 1
683
684     } else {
685         set notown 2
686         lappend note_missings [list $island $realname $vid]
687     }
688
689     lappend codel "$lock$notown" $xabbrev
690     lappend newnotes [list $vid $realname $owner $xabbrev]
691     set kk "$island [join $codel _]"
692     upvar #0 found($kk) k
693     lappend k [list $vid $realname $owner]
694  
695     debug "CODED $kk $vid $realname"
696 }
697
698 set clipboard {}
699 proc parse-clipboard {} {
700     global clipboard found notes notes_used newnotes
701
702     catch { unset found }
703     catch { unset notes_used }
704     glset note_infos {}
705     glset note_missings {}
706
707     set newnotes {}
708     
709     set itemre { (\w+) = ([^=]*) }
710     set manyitemre "^\\\[ $itemre ( (?: ,\\ $itemre)* ) \\]\$"
711     debug $manyitemre
712
713     set lno 0
714     foreach l [split $clipboard "\n"] {
715         incr lno
716         errexpect-setline $lno $l
717         if {![string length $l]} continue
718         catch { unset vi }
719         while 1 {
720                 if {![regexp -expanded $manyitemre $l dummy \
721                         thiskey thisval rhs]} {
722                     errexpect-error "badly formatted"
723                 }
724                 set vi($thiskey) $thisval
725                 if {![string length $rhs]} break
726                 regsub {^, } $rhs {} rhs
727                 set l "\[$rhs\]"
728         }
729         vessel vi
730     }
731
732     if {[llength $newnotes]} {
733         foreach vid [lsort [array names notes]] {
734             if {![info exists notes_used($vid)]} {
735                 manyset $notes($vid) lno notename
736                 note-info $lno $vid $notename {} \
737                     "vessel in notes no longer found"
738             }
739         }
740     }
741 }
742
743 proc load-clipboard-file {fn} {
744     set f [open $fn]
745     glset clipboard [read $f]
746     close $f
747 }
748
749
750 #---------- loading and parsing the chart ----------
751
752 proc load-chart {} {
753     global chart scraper
754     debug "FETCHING CHART"
755     set chart [eval exec $scraper [list | perl -we {
756         use strict;
757         use CommodsScrape;
758         use IO::File;
759         use IO::Handle;
760         yppedia_chart_parse(\*STDIN, (new IO::File ">/dev/null"),
761                 sub { sprintf "%d %d", @_; },
762                 sub { printf "archlabel %d %d %s\n", @_; },
763                 sub { printf "island %s {%s} %s\n", @_; },
764                 sub { printf "league %s %s %s.\n", @_; },
765                 sub { printf STDERR "warning: %s: incomprehensible: %s", @_; }
766                         );
767         STDOUT->error and die $!;
768     }]]
769 }
770
771
772 set scale 16
773
774 proc coord {c} {
775         global scale
776         return [expr {$c * $scale}]
777 }
778
779 proc chart-got/archlabel {args} { }
780 proc chart-got/island {x y isle sizecol} {
781         debug "ISLE $x $y $isle $sizecol"
782         global canvas isleloc
783         set isleloc($isle) [list $x $y]
784         set sz 5
785 #       $canvas create oval \
786 #               [expr {[coord $x] - $sz}] [expr {[coord $y] - $sz}] \
787 #               [expr {[coord $x] + $sz}] [expr {[coord $y] + $sz}] \
788 #               -fill blue
789         set colour "#888"
790         if {[string match *_col $sizecol]} { set colour black }
791         $canvas create text [coord $x] [coord $y] \
792                 -text $isle -anchor s -fill $colour
793 }
794 proc chart-got/league {x1 y1 x2 y2 kind} {
795 #       debug "LEAGUE $x1 $y1 $x2 $y2 $kind"
796         global canvas
797         set l [$canvas create line \
798                 [coord $x1] [coord $y1] \
799                 [coord $x2] [coord $y2]]
800         if {![string compare $kind .]} {
801                 $canvas itemconfigure $l -dash .
802         }
803 }
804
805 proc redraw-needed {} {
806     global redraw_after
807     debug "REDRAW NEEDED"
808     if {[info exists redraw_after]} return
809     set redraw_after [after 250 draw]
810 }
811
812 proc draw {} {
813     global chart found isleloc canvas redraw_after islandnames smfound
814
815     catch { after cancel $redraw_after }
816     catch { unset redraw_after }
817     
818     $canvas delete all
819
820     foreach l [split $chart "\n"] {
821 #       debug "CHART-GOT $l"
822         set proc [lindex $l 0]
823         eval chart-got/$proc [lrange $l 1 end]
824     }
825
826     catch { unset smfound }
827     foreach key [lsort [array names found]] {
828         regexp {^(.*) (\S+)$} $key dummy islandname code
829         set smcode [smash-code $code]
830         debug "smashed $code => $smcode"
831         set smkey "$islandname $smcode"
832         foreach vessel $found($key) { lappend smfound($smkey) $vessel }
833     }
834
835     set islandnames {}
836     set lastislandname {}
837     foreach smkey [lsort [array names smfound]] {
838         set c [llength $smfound($smkey)]
839 #       debug "SHOWING $smkey $c"
840         regexp {^(.*) (\S+)$} $smkey dummy islandname code
841
842         if {![filters-say-yes $code]} continue
843
844         if {[string compare $lastislandname $islandname]} {
845                 manyset $isleloc($islandname) x y
846                 set x [coord $x]
847                 set y [coord $y]
848                 set lastislandname $islandname
849                 lappend islandnames $islandname
850 #               debug "START Y $y"
851         }
852
853         if {$c > 1} { set qty [format %d $c] } else { set qty {} }
854         code2canvas $code $canvas $x y $qty 2 \
855             [list show-report $islandname $code]
856 #       debug "NEW Y $y"
857     }
858
859     panner::updatecanvas-bbox .cp.ctrl.pan
860
861     islandnames-update
862 }
863
864
865 #---------- parser error reporting ----------
866
867 proc parser-control-create {w base invokebuttontext etl_title} {
868     frame $w
869     button $w.do -text $invokebuttontext -command invoke_$base -pady 3
870
871     frame $w.resframe -width 120 -height 32
872     button $w.resframe.res -text {} -anchor nw \
873         -padx 1 -pady 1 -borderwidth 0 -justify left
874     glset deffont_$base [$w.resframe.res cget -font]
875     place $w.resframe.res -relx 0.5 -y 0 -anchor n
876
877     pack $w.do -side top
878     pack $w.resframe -side top -expand y -fill both
879
880     set eb .err_$base
881     toplevel $eb
882     wm withdraw $eb
883     wm title $eb "where-vessels - $etl_title"
884     wm protocol $eb WM_DELETE_WINDOW [list wm withdraw $eb]
885
886     label $eb.title -text $etl_title
887     pack $eb.title -side top
888
889     button $eb.close -text Close -command [list wm withdraw $eb]
890     pack $eb.close -side bottom
891
892     frame $eb.emsg -bd 2 -relief groove
893     label $eb.emsg.lab -anchor nw -text "Error:"
894     text $eb.emsg.text -height 1
895     pack $eb.emsg.text -side bottom -fill x
896     pack $eb.emsg.lab -side left
897
898     pack $eb.emsg -side top -pady 2 -fill x
899
900     frame $eb.text -bd 2 -relief groove
901     pack $eb.text -side bottom -pady 2 -fill both -expand y
902     
903     label $eb.text.lab -anchor nw
904
905     text $eb.text.text -width 85 \
906         -xscrollcommand [list $eb.text.xscroll set] \
907         -yscrollcommand [list $eb.text.yscroll set]
908     $eb.text.text tag configure error \
909         -background red -foreground white
910
911     scrollbar $eb.text.xscroll -orient horizontal \
912         -command [list $eb.text.text xview]
913     scrollbar $eb.text.yscroll -orient vertical \
914         -command [list $eb.text.text yview]
915
916     grid configure $eb.text.lab -row 0 -column 0 -sticky w -columnspan 2
917     grid configure $eb.text.text -row 1 -column 0 -sticky news
918     grid configure $eb.text.yscroll -sticky ns -row 1 -column 1
919     grid configure $eb.text.xscroll -sticky ew -row 2 -column 0
920     grid rowconfigure $eb.text 0 -weight 0
921     grid rowconfigure $eb.text 1 -weight 1
922     grid rowconfigure $eb.text 2 -weight 0
923     grid columnconfigure $eb.text 0 -weight 1
924     grid columnconfigure $eb.text 1 -weight 0
925 }
926
927 proc parser-control-ok-core {w base background show} {
928     debug "parser-control-ok-core $w $base $background $show"
929     upvar #0 deffont_$base deffont
930     $w.resframe.res configure \
931         -background $background -disabledforeground black -font $deffont \
932         -state disabled -command {} \
933         -text $show
934 }    
935 proc parser-control-ok {w base show} {
936     parser-control-ok-core $w $base green $show
937 }
938 proc parser-control-none {w base show} {
939     parser-control-ok-core $w $base blue $show
940 }
941 proc parser-control-failed-core {w base foreground background smallfont
942                                  tiny summary fulldesc fulldata} {
943     debug "parser-control-failed-core $w $base $summary $fulldesc"
944     upvar #0 deffont_$base deffont
945     set eb .err_$base
946
947     $eb.emsg.text delete 0.0 end
948     $eb.emsg.text insert end $summary
949
950     $eb.text.lab configure -text $fulldesc
951     $eb.text.text delete 0.0 end
952     $eb.text.text insert end $fulldata
953
954     regsub -all {.{18}} $tiny "&\n" ewrap
955
956     if {$smallfont} {
957         set font fixed
958     } else {
959         set font $deffont
960     }
961
962     $w.resframe.res configure \
963         -background $background -foreground $foreground -font $font \
964         -state normal -command [list wm deiconify $eb] \
965         -text $ewrap
966 }
967     
968 proc parser-control-failed-expected {w base emsg lno ei fulldesc newdata} {
969     set eb .err_$base
970
971     set line [lindex [split $ei "\n"] 0]
972     debug "parser-control-failed-expected: $w $base: $lno: $emsg\n $line"
973
974     parser-control-failed-core $w $base \
975         white red 1 \
976         "err: [string trim $emsg]: \"$line\"" \
977         "at line $lno: $emsg" \
978         $fulldesc $newdata
979
980     $eb.text.text tag add error $lno.0 $lno.end
981     $eb.text.text see $lno.0    
982 }
983 proc parser-control-failed-unexpected {w base emsg ei} {
984     global errorInfo
985     parser-control-failed-core $w $base \
986         black yellow 1 \
987         $emsg $emsg "Details and stack trace:" $ei
988 }
989
990 proc reparse {base varname old fulldesc okshow noneshow parse ok} {
991     upvar #0 $varname var
992     manyset [errexpect-catch {
993         uplevel 1 $parse
994         if {[string length [string trim $var]]} {
995             parser-control-ok .cp.ctrl.$base $base $okshow
996         } else {
997             parser-control-none .cp.ctrl.$base $base $noneshow
998         }
999     }] failed emsg lno ei
1000     if {$failed} {
1001         parser-control-failed-expected .cp.ctrl.$base $base \
1002             $emsg $lno $ei $fulldesc $var
1003         set var $old
1004         uplevel 1 $parse
1005     } else {
1006         uplevel 1 $ok
1007     }
1008 }
1009
1010 #---------- island names selection etc. ----------
1011
1012 proc islandnames-update {} {
1013     global islandnames
1014     .islands.count configure -text [format "ships at %d island(s)" \
1015                                         [llength $islandnames]]
1016 }
1017
1018 proc islandnames-select {} {
1019     .islands.clip configure -relief sunken -state disabled
1020     selection own -command islandnames-deselect .islands.clip
1021 }
1022 proc islandnames-deselect {} {
1023     .islands.clip configure -relief raised -state normal
1024 }
1025
1026 proc islandnames-handler {offset maxchars} {
1027     global islandnames
1028     return [string range [join $islandnames ", "] \
1029                 $offset [expr {$offset+$maxchars-1}]]
1030 }
1031
1032 #---------- main user interface ----------
1033
1034 proc widgets-setup {} {
1035     global canvas debug pirate ocean filterstyle
1036
1037     wm geometry . 1024x600
1038     wm title . "where-vessels - $pirate on the $ocean ocean"
1039
1040     #----- map -----
1041
1042     frame .f -border 1 -relief groove
1043     set canvas .f.c
1044     canvas $canvas
1045     pack $canvas -expand 1 -fill both
1046     pack .f -expand 1 -fill both -side left
1047
1048     #----- control panels and filter -----
1049
1050     frame .cp
1051     frame .smash -relief groove -bd 2 -padx 1
1052     frame .filter -relief groove -bd 2 -padx 1
1053     frame .islands -pady 2
1054     pack .cp .smash .filter .islands -side top
1055
1056     label .smash.title -text Smash
1057     pack .smash.title -side left
1058
1059     checkbutton .smash.subclass -text Subclass \
1060         -variable smash_subclass -command redraw-needed
1061     pack .smash.subclass -side left
1062
1063     set filterstyle 1
1064     trace add variable filterstyle write filterstyle-changed
1065
1066     frame .filter.title
1067     label .filter.title.title -text Show
1068     pack .filter.title.title -side left
1069     for {set fing 0} {$fing < 4} {incr fing} {
1070         radiobutton .filter.title.f$fing \
1071             -variable filterstyle -value $fing \
1072             -text [lindex {All Useable Mine These:} $fing]
1073         pack .filter.title.f$fing -side left
1074     }
1075
1076     grid configure .filter.title -row 0 -column 0 -columnspan 2
1077
1078     #----- control panel -----
1079
1080     frame .cp.ctrl
1081     pack .cp.ctrl -side left -anchor n
1082
1083     debug "BBOX [$canvas bbox all]"
1084
1085     panner::canvas-scroll-bbox .f.c
1086     panner::create .cp.ctrl.pan .f.c 120 120 $debug
1087
1088     pack .cp.ctrl.pan -side top -pady 0 -padx 5
1089     frame .cp.ctrl.zoom
1090     pack .cp.ctrl.zoom -side top
1091
1092     button .cp.ctrl.zoom.out -text - -font {Courier 16} -command {zoom /2} -pady 0
1093     button .cp.ctrl.zoom.in  -text + -font {Courier 16} -command {zoom *2} -pady 0
1094     pack .cp.ctrl.zoom.out .cp.ctrl.zoom.in -side left
1095
1096     parser-control-create .cp.ctrl.acquire \
1097         acquire Acquire \
1098         "Clipboard parsing error" \
1099         
1100     pack .cp.ctrl.acquire -side top -pady 2
1101
1102     parser-control-create .cp.ctrl.notes \
1103         notes "Reload notes" \
1104         "Vessel notes loading report" \
1105         
1106     pack .cp.ctrl.notes -side top -pady 2
1107
1108     #----- island name count and copy -----
1109
1110     label .islands.count
1111     button .islands.clip -text "copy island names" -pady 2 -padx 2 \
1112          -command islandnames-select
1113     selection handle .islands.clip islandnames-handler
1114     pack .islands.count .islands.clip -side left
1115
1116     #----- decoding etc. report -----
1117
1118     frame .cp.report
1119     pack .cp.report -side left -anchor n
1120
1121     label .cp.report.island -text { }
1122
1123     canvas .cp.report.abbrev -width 1 -height 15
1124
1125     frame .cp.report.code
1126     label .cp.report.code.lab -text Code:
1127     glset report_code { }
1128     entry .cp.report.code.code -state readonly \
1129         -textvariable report_code -width 15
1130     pack .cp.report.code.lab .cp.report.code.code -side left
1131     frame .cp.report.details -bd 2 -relief groove -padx 2 -pady 2
1132
1133     listbox .cp.report.list -height 5
1134
1135     pack .cp.report.island .cp.report.abbrev .cp.report.details \
1136         .cp.report.list -side top
1137     #pack .cp.report.code -side top
1138     pack configure .cp.report.details -fill x
1139
1140     foreach sw {inport class subclass lock own xabbrev} {
1141         label .cp.report.details.$sw -text { }
1142         pack .cp.report.details.$sw -side top -anchor w
1143     }
1144 }
1145
1146 proc report-set {sw val} { .cp.report.details.$sw configure -text $val }
1147
1148 proc show-report {islandname code} {
1149     .cp.report.island configure -text $islandname
1150
1151     .cp.report.abbrev delete all
1152     set y 2
1153     code2canvas $code .cp.report.abbrev 5 y {} 0 {}
1154     manyset [.cp.report.abbrev bbox all] minx dummy maxx dummy
1155     .cp.report.abbrev configure -width [expr {$maxx-$minx+4}]
1156
1157     glset report_code $code
1158     show-report-decode $code
1159
1160     set kk "$islandname $code"
1161     upvar #0 smfound($kk) k
1162
1163     .cp.report.list delete 0 end
1164
1165     foreach entry $k {
1166         manyset $entry vid name owner
1167         lappend owned($owner) $name
1168     }
1169
1170     foreach owner [lsort [array names owned]] {
1171         if {[string length $owner]} {
1172             set owndesc "$owner's"
1173         } else {
1174             set owndesc "Owner unknown"
1175         }
1176         .cp.report.list insert end "$owndesc:"
1177         foreach name $owned($owner) {
1178             .cp.report.list insert end " $name"
1179         }
1180     }
1181 }
1182
1183 proc zoom {extail} {
1184     global scale canvas
1185     set nscale [expr "\$scale $extail"]
1186     debug "ZOOM $scale $nscale"
1187     if {$nscale < 1 || $nscale > 200} return
1188     set scale $nscale
1189     draw
1190 }
1191
1192 proc invoke_acquire {} {
1193     global clipboard errorInfo
1194     set old $clipboard
1195
1196     if {[catch {
1197         set clipboard [clipboard get]
1198     } emsg]} {
1199         parser-control-failed-unexpected .cp.ctrl.acquire acquire \
1200             $emsg "fetching clipboard:\n\n$errorInfo"
1201         return
1202     }
1203
1204     reparse acquire \
1205         clipboard $old "Clipboard contents:" { acquired ok } { no vessels } {
1206             parse-clipboard
1207         } {
1208             display-note-infos
1209         }
1210     draw
1211 }
1212
1213 proc invoke_notes {} {
1214     global notes_data errorInfo notes_loc
1215     set old $notes_data
1216     
1217     if {[catch {
1218         load-notes
1219     } emsg]} {
1220         parser-control-failed-unexpected .cp.ctrl.notes notes \
1221             $emsg "loading $notes_loc:\n\n$errorInfo"
1222         return
1223     }
1224
1225     reparse notes \
1226         notes_data $old "Vessel notes:" "loaded ok" { no notes } {
1227             parse-notes
1228             parse-clipboard
1229         } {
1230             display-note-infos
1231         }
1232     draw
1233 }
1234
1235 #---------- main program ----------
1236
1237 parseargs
1238 argdefaults
1239 httpclientsetup where-vessels
1240 info-cache-update
1241 vesselclasses-init
1242 load-chart
1243 widgets-setup
1244 make-filters
1245
1246 set notes_data {}
1247 if {[catch { parse-clipboard } emsg]} {
1248     puts stderr "$emsg\n$errorInfo"
1249     exit 1
1250 }
1251 after idle invoke_notes
1252
1253 draw
1254
1255 # rsync -r --exclude=\*~ yarrg/icons/. ijackson@chiark.greenend.org.uk:/home/ftp/users/ijackson/yarrg/vessel-info/.