chiark / gitweb /
where-vessels: Use grid for smashing too
[ypp-sc-tools.web-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 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 > 1} {
448         set subclass {}
449     } elseif {$smash_subclass && [string length $subclass]} {
450         set subclass !
451     }
452
453     return [join [list $inport $class $subclass $lockown $xabbrev] _]
454 }
455
456 proc make-smasher {sma label ekind} {
457     return [make-gridded-control .smash $sma $label $ekind]
458 }
459
460 proc make-radio-smasher {sma label variable descs} {
461     set w [make-smasher $sma $label frame]
462     for {set i 0} {$i < [llength $descs]} {incr i} {
463         radiobutton $w.v$i \
464             -variable $variable -value $i -command redraw-needed \
465             -text [lindex $descs $i]
466         pack $w.v$i -side left
467     }
468 }
469
470 #---------- filtering ----------
471
472 set filters {}
473
474 proc filter-values/size {} { global vc_codes; return $vc_codes }
475 proc filter-icon/size {code} {
476     upvar #0 vc_code2abbrev($code) abb
477     return icon/$abb
478 }
479 proc filter-default/size {code} { return 1 }
480 proc filter-says-yes/size {codel} {
481     set sizecode [lindex $codel 1]
482     upvar #0 filter_size($sizecode) yes
483     return $yes
484 }
485
486 proc filter-values/lockown {} {
487     foreach lv {0 1 2} {
488         foreach ov {0 1 2} {
489             lappend vals "$lv$ov"
490         }
491     }
492     return $vals
493 }
494 proc filter-icon/lockown {lockown} { return [code-lockown2icon $lockown] }
495 proc filter-default/lockown {lockown} {
496     return [regexp {^[01]|^2[^1]} $lockown]
497 }
498 proc filter-says-yes/lockown {codel} {
499     set lockown [lindex $codel 3]
500     upvar #0 filter_lockown($lockown) yes
501     return $yes
502 }
503
504 proc filter-validate/xabbre {re} {
505     if {[catch {
506         regexp -- $re {}
507     } emsg]} {
508         regsub {^.*:\s*} $emsg {} emsg
509         regsub {^.*(.{30})$} $emsg {\1} emsg
510         return $emsg
511     }
512     return {}
513 }
514 proc filter-says-yes/xabbre {codel} {
515     global filter_xabbre
516     set xabbrev [lindex $codel 4]
517     return [regexp -- $filter_xabbre $xabbrev]
518 }
519
520 proc filter-tickbox-flip {fil} {
521     upvar #0 filter_$fil vars
522     set values [filter-values/$fil]
523     foreach val $values {
524         set vars($val) [expr {!$vars($val)}]
525     }
526     redraw-needed
527 }
528
529 proc make-tickbox-filter {fil label rows inrow} {
530     upvar #0 filter_$fil vars
531     set fw [make-filter $fil $label frame]
532     set values [filter-values/$fil]
533     set nvalues [llength $values]
534     if {!$inrow} {
535         set inrow [expr {($nvalues + $rows) / $rows}]
536     }
537     set noicons [catch { info args filter-icon/$fil }]
538     for {set ix 0} {$ix < $nvalues} {incr ix} {
539         set val [lindex $values $ix]
540         set vars($val) [filter-default/$fil $val]
541         checkbutton $fw.$ix -variable filter_${fil}($val) \
542             -font fixed -command redraw-needed
543         if {!$noicons} {
544             $fw.$ix configure -image [filter-icon/$fil $val] -height 16
545         } else {
546             $fw.$ix configure -text [filter-map/$fil $val]
547         }
548         grid configure $fw.$ix -sticky sw \
549             -row [expr {$ix / $inrow}] \
550             -column [expr {$ix % $inrow}]
551     }
552     button $fw.invert -text flip -command [list filter-tickbox-flip $fil] \
553         -padx 0 -pady 0
554     grid configure $fw.invert -sticky se \
555         -row [expr {$rows-1}] \
556         -column [expr {$inrow-1}]
557 }
558
559 proc entry-filter-changed {fw fil n1 n2 op} {
560     global errorInfo
561     upvar #0 filter_$fil realvar
562     upvar #0 filterentered_$fil entryvar
563     global def_background
564     debug "entry-filter-changed $fw $fil $entryvar"
565     if {[catch {
566         set error [filter-validate/$fil $entryvar]
567         if {[string length $error]} {
568             $fw.error configure -text $error -foreground white -background red
569         } else {
570             $fw.error configure -text { } -background $def_background
571             set realvar $entryvar
572             redraw-needed
573         }
574     } emsg]} {
575         puts stderr "FILTER CHECK ERROR $emsg $errorInfo"
576     }
577 }
578
579 proc make-entry-filter {fil label def} {
580     global filterentered_$fil
581     upvar #0 filter_$fil realvar
582     set realvar $def
583     set fw [make-filter $fil $label frame]
584     entry $fw.entry -textvariable filterentered_$fil
585     label $fw.error
586     glset def_background [$fw.error cget -background]
587     trace add variable filterentered_$fil write \
588         [list entry-filter-changed $fw $fil]
589     pack $fw.entry $fw.error -side top -anchor w
590 }
591
592 proc make-gridded-control {parent name label ekind} {
593     debug "MAKE-GRIDDED-CONTROL [list $parent $name $label $ekind]"
594     label $parent.lab_$name -text $label -justify left
595     $ekind $parent.$name
596     manyset [grid size $parent] dummy row
597     incr row
598     grid configure $parent.lab_$name -row $row -column 0 -sticky nw -pady 4
599     grid configure $parent.$name -row $row -column 1 -sticky w -pady 3
600     return $parent.$name
601 }
602
603 proc make-filter {fil label ekind} {
604     global filters
605     lappend filters $fil
606     return [make-gridded-control .filter $fil $label $ekind]
607 }
608
609 proc make-filters {} {
610     make-tickbox-filter size Size 2 0
611     make-tickbox-filter lockown "Lock/\nowner" 2 6
612     make-entry-filter xabbre "Flags\n regexp" {}
613 }
614
615 proc filterstyle-changed {n1 n2 op} {
616     global filterstyle
617     debug "filterstyle-changed $filterstyle"
618     redraw-needed
619 }
620
621 proc filters-say-yes {code} {
622     global filters filterstyle
623     debug "filters-say-yes $code"
624     set codel [split $code _]
625     set lockown [lindex $codel 3]
626     switch -exact $filterstyle {
627         0 { return 1 }
628         1 { return [filter-default/lockown $lockown] }
629         2 { return [regexp {^.0} $lockown] }
630         3 { }
631         default { error $filterstyle }
632     }
633     
634     foreach fil $filters {
635         if {![filter-says-yes/$fil $codel]} { return 0 }
636     }
637     return 1
638 }
639     
640 #---------- loading and parsing the clipboard (vessel locations) ----------
641
642 proc vessel {vin} {
643     global pirate notes_used note_missings newnotes
644     upvar 1 $vin vi
645
646     set codel {}
647     lappend codel [errexpect-arrayget-boolean vi inPort]
648
649     set gameclass [errexpect-arrayget vi vesselClass]
650     upvar #0 vc_game2code($gameclass) class
651     if {![info exists class]} {
652         set class "($gameclass)"
653         upvar #0 vc_code2abbrev($class) vcabb
654         set vcabb vc-$class
655         set data [exec pbmtext -builtin fixed " $gameclass " \
656                  | pnminvert | pnmcrop | pbmtoxbm]
657         debug "INVENTED ICON $vcabb $data"
658         image create bitmap icon/$vcabb -data $data
659             
660         global vc_code2full
661         set vc_code2full($class) "Type \"$gameclass\""
662     }
663     lappend codel $class
664
665     set gamesubclass [errexpect-arrayget vi vesselSubclass]
666     upvar #0 vsc_game2code($gamesubclass) subclass
667     if {[info exists subclass]} {
668         lappend codel $subclass
669     } else {
670         lappend codel ($gamesubclass)
671     }
672
673     switch -exact [errexpect-arrayget vi isLocked]/[ \
674                    errexpect-arrayget vi isBattleReady] {
675         true/false      { set lock 2 }
676         false/false     { set lock 1 }
677         false/true      { set lock 0 }
678         default         { errexpect-error "unexpected isLocked/isBattleReady" }
679     }
680
681     set vid [errexpect-arrayget vi vesselId]
682     upvar #0 notes($vid) note
683     set realname [errexpect-arrayget vi vesselName]
684     set island [errexpect-arrayget vi islandName]
685
686     set owner {}
687     set xabbrev {}
688     if {[info exists note]} {
689         manyset $note lno notename owner xabbrev
690         if {[string compare -nocase $realname $notename]} {
691             note-info $lno $vid $realname $island \
692                 "notes say name is $notename"
693         }
694         if {[string length $owner]} {
695             if {![string compare $owner $pirate]} {
696                 set notown 0
697             } else {
698                 set notown 1
699             }
700         } else {
701             set notown 2
702         }
703         append abbrev $xabbrev
704         set notes_used($vid) 1
705
706     } else {
707         set notown 2
708         lappend note_missings [list $island $realname $vid]
709     }
710
711     lappend codel "$lock$notown" $xabbrev
712     lappend newnotes [list $vid $realname $owner $xabbrev]
713     set kk "$island [join $codel _]"
714     upvar #0 found($kk) k
715     lappend k [list $vid $realname $owner]
716  
717     debug "CODED $kk $vid $realname"
718 }
719
720 set clipboard {}
721 proc parse-clipboard {} {
722     global clipboard found notes notes_used newnotes
723
724     catch { unset found }
725     catch { unset notes_used }
726     glset note_infos {}
727     glset note_missings {}
728
729     set newnotes {}
730     
731     set itemre { (\w+) = ([^=]*) }
732     set manyitemre "^\\\[ $itemre ( (?: ,\\ $itemre)* ) \\]\$"
733     debug $manyitemre
734
735     set lno 0
736     foreach l [split $clipboard "\n"] {
737         incr lno
738         errexpect-setline $lno $l
739         if {![string length $l]} continue
740         catch { unset vi }
741         while 1 {
742                 if {![regexp -expanded $manyitemre $l dummy \
743                         thiskey thisval rhs]} {
744                     errexpect-error "badly formatted"
745                 }
746                 set vi($thiskey) $thisval
747                 if {![string length $rhs]} break
748                 regsub {^, } $rhs {} rhs
749                 set l "\[$rhs\]"
750         }
751         vessel vi
752     }
753
754     if {[llength $newnotes]} {
755         foreach vid [lsort [array names notes]] {
756             if {![info exists notes_used($vid)]} {
757                 manyset $notes($vid) lno notename
758                 note-info $lno $vid $notename {} \
759                     "vessel in notes no longer found"
760             }
761         }
762     }
763 }
764
765 proc load-clipboard-file {fn} {
766     set f [open $fn]
767     glset clipboard [read $f]
768     close $f
769 }
770
771
772 #---------- loading and parsing the chart ----------
773
774 proc load-chart {} {
775     global chart scraper
776     debug "FETCHING CHART"
777     set chart [eval exec $scraper [list | perl -we {
778         use strict;
779         use CommodsScrape;
780         use IO::File;
781         use IO::Handle;
782         yppedia_chart_parse(\*STDIN, (new IO::File ">/dev/null"),
783                 sub { sprintf "%d %d", @_; },
784                 sub { printf "archlabel %d %d %s\n", @_; },
785                 sub { printf "island %s {%s} %s\n", @_; },
786                 sub { printf "league %s %s %s.\n", @_; },
787                 sub { printf STDERR "warning: %s: incomprehensible: %s", @_; }
788                         );
789         STDOUT->error and die $!;
790     }]]
791 }
792
793
794 set scale 16
795
796 proc coord {c} {
797         global scale
798         return [expr {$c * $scale}]
799 }
800
801 proc chart-got/archlabel {args} { }
802 proc chart-got/island {x y isle sizecol} {
803         debug "ISLE $x $y $isle $sizecol"
804         global canvas isleloc
805         set isleloc($isle) [list $x $y]
806         set sz 5
807 #       $canvas create oval \
808 #               [expr {[coord $x] - $sz}] [expr {[coord $y] - $sz}] \
809 #               [expr {[coord $x] + $sz}] [expr {[coord $y] + $sz}] \
810 #               -fill blue
811         set colour "#888"
812         if {[string match *_col $sizecol]} { set colour black }
813         $canvas create text [coord $x] [coord $y] \
814                 -text $isle -anchor s -fill $colour
815 }
816 proc chart-got/league {x1 y1 x2 y2 kind} {
817 #       debug "LEAGUE $x1 $y1 $x2 $y2 $kind"
818         global canvas
819         set l [$canvas create line \
820                 [coord $x1] [coord $y1] \
821                 [coord $x2] [coord $y2]]
822         if {![string compare $kind .]} {
823                 $canvas itemconfigure $l -dash .
824         }
825 }
826
827 proc redraw-needed {} {
828     global redraw_after
829     debug "REDRAW NEEDED"
830     if {[info exists redraw_after]} return
831     set redraw_after [after 250 draw]
832 }
833
834 proc draw {} {
835     global chart found isleloc canvas redraw_after islandnames smfound
836
837     catch { after cancel $redraw_after }
838     catch { unset redraw_after }
839     
840     $canvas delete all
841
842     foreach l [split $chart "\n"] {
843 #       debug "CHART-GOT $l"
844         set proc [lindex $l 0]
845         eval chart-got/$proc [lrange $l 1 end]
846     }
847
848     catch { unset smfound }
849     foreach key [lsort [array names found]] {
850         regexp {^(.*) (\S+)$} $key dummy islandname code
851         set smcode [smash-code $code]
852         debug "smashed $code => $smcode"
853         set smkey "$islandname $smcode"
854         foreach vessel $found($key) { lappend smfound($smkey) $vessel }
855     }
856
857     set islandnames {}
858     set lastislandname {}
859     foreach smkey [lsort [array names smfound]] {
860         set c [llength $smfound($smkey)]
861 #       debug "SHOWING $smkey $c"
862         regexp {^(.*) (\S+)$} $smkey dummy islandname code
863
864         if {![filters-say-yes $code]} continue
865
866         if {[string compare $lastislandname $islandname]} {
867                 manyset $isleloc($islandname) x y
868                 set x [coord $x]
869                 set y [coord $y]
870                 set lastislandname $islandname
871                 lappend islandnames $islandname
872 #               debug "START Y $y"
873         }
874
875         if {$c > 1} { set qty [format %d $c] } else { set qty {} }
876         code2canvas $code $canvas $x y $qty 2 \
877             [list show-report $islandname $code]
878 #       debug "NEW Y $y"
879     }
880
881     panner::updatecanvas-bbox .cp.ctrl.pan
882
883     islandnames-update
884 }
885
886
887 #---------- parser error reporting ----------
888
889 proc parser-control-create {w base invokebuttontext etl_title} {
890     frame $w
891     button $w.do -text $invokebuttontext -command invoke_$base -pady 3
892
893     frame $w.resframe -width 120 -height 32
894     button $w.resframe.res -text {} -anchor nw \
895         -padx 1 -pady 1 -borderwidth 0 -justify left
896     glset deffont_$base [$w.resframe.res cget -font]
897     place $w.resframe.res -relx 0.5 -y 0 -anchor n
898
899     pack $w.do -side top
900     pack $w.resframe -side top -expand y -fill both
901
902     set eb .err_$base
903     toplevel $eb
904     wm withdraw $eb
905     wm title $eb "where-vessels - $etl_title"
906     wm protocol $eb WM_DELETE_WINDOW [list wm withdraw $eb]
907
908     label $eb.title -text $etl_title
909     pack $eb.title -side top
910
911     button $eb.close -text Close -command [list wm withdraw $eb]
912     pack $eb.close -side bottom
913
914     frame $eb.emsg -bd 2 -relief groove
915     label $eb.emsg.lab -anchor nw -text "Error:"
916     text $eb.emsg.text -height 1
917     pack $eb.emsg.text -side bottom -fill x
918     pack $eb.emsg.lab -side left
919
920     pack $eb.emsg -side top -pady 2 -fill x
921
922     frame $eb.text -bd 2 -relief groove
923     pack $eb.text -side bottom -pady 2 -fill both -expand y
924     
925     label $eb.text.lab -anchor nw
926
927     text $eb.text.text -width 85 \
928         -xscrollcommand [list $eb.text.xscroll set] \
929         -yscrollcommand [list $eb.text.yscroll set]
930     $eb.text.text tag configure error \
931         -background red -foreground white
932
933     scrollbar $eb.text.xscroll -orient horizontal \
934         -command [list $eb.text.text xview]
935     scrollbar $eb.text.yscroll -orient vertical \
936         -command [list $eb.text.text yview]
937
938     grid configure $eb.text.lab -row 0 -column 0 -sticky w -columnspan 2
939     grid configure $eb.text.text -row 1 -column 0 -sticky news
940     grid configure $eb.text.yscroll -sticky ns -row 1 -column 1
941     grid configure $eb.text.xscroll -sticky ew -row 2 -column 0
942     grid rowconfigure $eb.text 0 -weight 0
943     grid rowconfigure $eb.text 1 -weight 1
944     grid rowconfigure $eb.text 2 -weight 0
945     grid columnconfigure $eb.text 0 -weight 1
946     grid columnconfigure $eb.text 1 -weight 0
947 }
948
949 proc parser-control-ok-core {w base background show} {
950     debug "parser-control-ok-core $w $base $background $show"
951     upvar #0 deffont_$base deffont
952     $w.resframe.res configure \
953         -background $background -disabledforeground black -font $deffont \
954         -state disabled -command {} \
955         -text $show
956 }    
957 proc parser-control-ok {w base show} {
958     parser-control-ok-core $w $base green $show
959 }
960 proc parser-control-none {w base show} {
961     parser-control-ok-core $w $base blue $show
962 }
963 proc parser-control-failed-core {w base foreground background smallfont
964                                  tiny summary fulldesc fulldata} {
965     debug "parser-control-failed-core $w $base $summary $fulldesc"
966     upvar #0 deffont_$base deffont
967     set eb .err_$base
968
969     $eb.emsg.text delete 0.0 end
970     $eb.emsg.text insert end $summary
971
972     $eb.text.lab configure -text $fulldesc
973     $eb.text.text delete 0.0 end
974     $eb.text.text insert end $fulldata
975
976     regsub -all {.{18}} $tiny "&\n" ewrap
977
978     if {$smallfont} {
979         set font fixed
980     } else {
981         set font $deffont
982     }
983
984     $w.resframe.res configure \
985         -background $background -foreground $foreground -font $font \
986         -state normal -command [list wm deiconify $eb] \
987         -text $ewrap
988 }
989     
990 proc parser-control-failed-expected {w base emsg lno ei fulldesc newdata} {
991     set eb .err_$base
992
993     set line [lindex [split $ei "\n"] 0]
994     debug "parser-control-failed-expected: $w $base: $lno: $emsg\n $line"
995
996     parser-control-failed-core $w $base \
997         white red 1 \
998         "err: [string trim $emsg]: \"$line\"" \
999         "at line $lno: $emsg" \
1000         $fulldesc $newdata
1001
1002     $eb.text.text tag add error $lno.0 $lno.end
1003     $eb.text.text see $lno.0    
1004 }
1005 proc parser-control-failed-unexpected {w base emsg ei} {
1006     global errorInfo
1007     parser-control-failed-core $w $base \
1008         black yellow 1 \
1009         $emsg $emsg "Details and stack trace:" $ei
1010 }
1011
1012 proc reparse {base varname old fulldesc okshow noneshow parse ok} {
1013     upvar #0 $varname var
1014     manyset [errexpect-catch {
1015         uplevel 1 $parse
1016         if {[string length [string trim $var]]} {
1017             parser-control-ok .cp.ctrl.$base $base $okshow
1018         } else {
1019             parser-control-none .cp.ctrl.$base $base $noneshow
1020         }
1021     }] failed emsg lno ei
1022     if {$failed} {
1023         parser-control-failed-expected .cp.ctrl.$base $base \
1024             $emsg $lno $ei $fulldesc $var
1025         set var $old
1026         uplevel 1 $parse
1027     } else {
1028         uplevel 1 $ok
1029     }
1030 }
1031
1032 #---------- island names selection etc. ----------
1033
1034 proc islandnames-update {} {
1035     global islandnames
1036     .islands.count configure -text [format "ships at %d island(s)" \
1037                                         [llength $islandnames]]
1038 }
1039
1040 proc islandnames-select {} {
1041     .islands.clip configure -relief sunken -state disabled
1042     selection own -command islandnames-deselect .islands.clip
1043 }
1044 proc islandnames-deselect {} {
1045     .islands.clip configure -relief raised -state normal
1046 }
1047
1048 proc islandnames-handler {offset maxchars} {
1049     global islandnames
1050     return [string range [join $islandnames ", "] \
1051                 $offset [expr {$offset+$maxchars-1}]]
1052 }
1053
1054 #---------- main user interface ----------
1055
1056 proc widgets-setup {} {
1057     global canvas debug pirate ocean filterstyle
1058
1059     wm geometry . 1024x600
1060     wm title . "where-vessels - $pirate on the $ocean ocean"
1061
1062     #----- map -----
1063
1064     frame .f -border 1 -relief groove
1065     set canvas .f.c
1066     canvas $canvas
1067     pack $canvas -expand 1 -fill both
1068     pack .f -expand 1 -fill both -side left
1069
1070     #----- control panels and filter -----
1071
1072     frame .cp
1073     frame .smash -relief groove -bd 2 -padx 1
1074     frame .filter -relief groove -bd 2 -padx 1
1075     frame .islands -pady 2
1076     pack .cp .filter .islands .smash -side top
1077
1078     label .smash.title -text Smash
1079     grid .smash.title -row 0 -column 0 -columnspan 2
1080
1081     make-radio-smasher subclass Subclass smash_subclass \
1082         {Show Normal/LE Hide}
1083
1084     set filterstyle 1
1085     trace add variable filterstyle write filterstyle-changed
1086
1087     frame .filter.title
1088     label .filter.title.title -text Show
1089     pack .filter.title.title -side left
1090     for {set fing 0} {$fing < 4} {incr fing} {
1091         radiobutton .filter.title.f$fing \
1092             -variable filterstyle -value $fing \
1093             -text [lindex {All Useable Mine These:} $fing]
1094         pack .filter.title.f$fing -side left
1095     }
1096
1097     grid configure .filter.title -row 0 -column 0 -columnspan 2
1098
1099     #----- control panel -----
1100
1101     frame .cp.ctrl
1102     pack .cp.ctrl -side left -anchor n
1103
1104     debug "BBOX [$canvas bbox all]"
1105
1106     panner::canvas-scroll-bbox .f.c
1107     panner::create .cp.ctrl.pan .f.c 120 120 $debug
1108
1109     pack .cp.ctrl.pan -side top -pady 0 -padx 5
1110     frame .cp.ctrl.zoom
1111     pack .cp.ctrl.zoom -side top
1112
1113     button .cp.ctrl.zoom.out -text - -font {Courier 16} -command {zoom /2} -pady 0
1114     button .cp.ctrl.zoom.in  -text + -font {Courier 16} -command {zoom *2} -pady 0
1115     pack .cp.ctrl.zoom.out .cp.ctrl.zoom.in -side left
1116
1117     parser-control-create .cp.ctrl.acquire \
1118         acquire Acquire \
1119         "Clipboard parsing error" \
1120         
1121     pack .cp.ctrl.acquire -side top -pady 2
1122
1123     parser-control-create .cp.ctrl.notes \
1124         notes "Reload notes" \
1125         "Vessel notes loading report" \
1126         
1127     pack .cp.ctrl.notes -side top -pady 2
1128
1129     #----- island name count and copy -----
1130
1131     label .islands.count
1132     button .islands.clip -text "copy island names" -pady 2 -padx 2 \
1133          -command islandnames-select
1134     selection handle .islands.clip islandnames-handler
1135     pack .islands.count .islands.clip -side left
1136
1137     #----- decoding etc. report -----
1138
1139     frame .cp.report
1140     pack .cp.report -side left -anchor n
1141
1142     label .cp.report.island -text { }
1143
1144     canvas .cp.report.abbrev -width 1 -height 15
1145
1146     frame .cp.report.code
1147     label .cp.report.code.lab -text Code:
1148     glset report_code { }
1149     entry .cp.report.code.code -state readonly \
1150         -textvariable report_code -width 15
1151     pack .cp.report.code.lab .cp.report.code.code -side left
1152     frame .cp.report.details -bd 2 -relief groove -padx 2 -pady 2
1153
1154     listbox .cp.report.list -height 5
1155
1156     pack .cp.report.island .cp.report.abbrev .cp.report.details \
1157         .cp.report.list -side top
1158     #pack .cp.report.code -side top
1159     pack configure .cp.report.details -fill x
1160
1161     foreach sw {inport class subclass lock own xabbrev} {
1162         label .cp.report.details.$sw -text { }
1163         pack .cp.report.details.$sw -side top -anchor w
1164     }
1165 }
1166
1167 proc report-set {sw val} { .cp.report.details.$sw configure -text $val }
1168
1169 proc show-report {islandname code} {
1170     .cp.report.island configure -text $islandname
1171
1172     .cp.report.abbrev delete all
1173     set y 2
1174     code2canvas $code .cp.report.abbrev 5 y {} 0 {}
1175     manyset [.cp.report.abbrev bbox all] minx dummy maxx dummy
1176     .cp.report.abbrev configure -width [expr {$maxx-$minx+4}]
1177
1178     glset report_code $code
1179     show-report-decode $code
1180
1181     set kk "$islandname $code"
1182     upvar #0 smfound($kk) k
1183
1184     .cp.report.list delete 0 end
1185
1186     foreach entry $k {
1187         manyset $entry vid name owner
1188         lappend owned($owner) $name
1189     }
1190
1191     foreach owner [lsort [array names owned]] {
1192         if {[string length $owner]} {
1193             set owndesc "$owner's"
1194         } else {
1195             set owndesc "Owner unknown"
1196         }
1197         .cp.report.list insert end "$owndesc:"
1198         foreach name $owned($owner) {
1199             .cp.report.list insert end " $name"
1200         }
1201     }
1202 }
1203
1204 proc zoom {extail} {
1205     global scale canvas
1206     set nscale [expr "\$scale $extail"]
1207     debug "ZOOM $scale $nscale"
1208     if {$nscale < 1 || $nscale > 200} return
1209     set scale $nscale
1210     draw
1211 }
1212
1213 proc invoke_acquire {} {
1214     global clipboard errorInfo
1215     set old $clipboard
1216
1217     if {[catch {
1218         set clipboard [clipboard get]
1219     } emsg]} {
1220         parser-control-failed-unexpected .cp.ctrl.acquire acquire \
1221             $emsg "fetching clipboard:\n\n$errorInfo"
1222         return
1223     }
1224
1225     reparse acquire \
1226         clipboard $old "Clipboard contents:" { acquired ok } { no vessels } {
1227             parse-clipboard
1228         } {
1229             display-note-infos
1230         }
1231     draw
1232 }
1233
1234 proc invoke_notes {} {
1235     global notes_data errorInfo notes_loc
1236     set old $notes_data
1237     
1238     if {[catch {
1239         load-notes
1240     } emsg]} {
1241         parser-control-failed-unexpected .cp.ctrl.notes notes \
1242             $emsg "loading $notes_loc:\n\n$errorInfo"
1243         return
1244     }
1245
1246     reparse notes \
1247         notes_data $old "Vessel notes:" "loaded ok" { no notes } {
1248             parse-notes
1249             parse-clipboard
1250         } {
1251             display-note-infos
1252         }
1253     draw
1254 }
1255
1256 #---------- main program ----------
1257
1258 parseargs
1259 argdefaults
1260 httpclientsetup where-vessels
1261 info-cache-update
1262 vesselclasses-init
1263 load-chart
1264 widgets-setup
1265 make-filters
1266
1267 set notes_data {}
1268 if {[catch { parse-clipboard } emsg]} {
1269     puts stderr "$emsg\n$errorInfo"
1270     exit 1
1271 }
1272 after idle invoke_notes
1273
1274 draw
1275
1276 # rsync -r --exclude=\*~ yarrg/icons/. ijackson@chiark.greenend.org.uk:/home/ftp/users/ijackson/yarrg/vessel-info/.