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