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