chiark / gitweb /
where-vessels: fix bugs due to split code and abbrev
[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
107 proc parseargs {} {
108     global ai argv
109     global debug scraper
110     set ai 0
111
112     while {[regexp {^\-} [set arg [lindex $argv $ai]]]} {
113         incr ai
114         switch -exact -- $arg {
115             -- { break }
116             --pirate { glset pirate [string totitle [nextarg]] }
117             --ocean { glset ocean [string totitle [nextarg]] }
118             --clipboard-file { load-clipboard-file [nextarg] }
119             --local-html-dir { lappend scraper --local-html-dir=[nextarg] }
120             --notes { glset notes_loc [nextarg] }
121             --debug { incr debug }
122             default { badusage "unknown option $arg" }
123         }
124     }
125     set argv [lrange $argv $ai end]
126     if {[llength $argv]} { badusage "non-option args not allowed" }
127 }
128
129 proc argdefaults {} {
130     global ocean notes_loc pirate scraper
131     if {![info exists ocean] || ![info exists pirate]} {
132         set cmd {./yarrg --find-window-only --quiet}
133         if {[info exists ocean]} { lappend cmd --ocean $ocean }
134         if {[info exists pirate]} { lappend cmd --pirate $pirate }
135         manyset [split [eval exec $cmd] " "] ocean pirate
136     }
137     lappend scraper $ocean
138 }
139
140
141 #---------- loading and parsing the vessel notes ----------
142
143 proc load-notes {} {
144     global notes_loc notes_data
145     if {[regexp {^\w+\:} $notes_loc]} {
146         update
147         debug "FETCHING NOTES $notes_loc"
148         set req [::http::geturl $notes_loc]
149         switch -glob [::http::status $req].[::http::ncode $req] {
150             ok.200 { }
151             ok.* { error "retrieving vessel-notes: [::http::code $req]" }
152             * { error "Retrieving vessel-notes: [::http::error $req]" }
153         }
154         set newdata [::http::data $req]
155         ::http::cleanup $req
156     } else {
157         debug "READING NOTES $notes_loc"
158         set vn [open $notes_loc]
159         set newdata [read $vn]
160         close $vn
161     }
162     set notes_data $newdata
163 }
164
165 proc parse-notes {} {
166     global notes_data notes
167     catch { unset notes }
168
169     set lno 0
170     foreach l [split $notes_data "\n"] {
171         incr lno
172         errexpect-setline $lno $l
173         set l [string trim $l]
174         if {![string length $l]} continue
175         if {[regexp {^\#} $l]} continue
176         if {![regexp -expanded \
177                   {^ (\d+) (?: \s+([^=]*?) )? \s* =
178                       (?: \s* (\S+)
179                        (?: \s+ (\S+) )?)? $} \
180                   $l dummy vid vname owner note]} {
181               errexpect-error "badly formatted"
182         }
183         set vname [string trim $vname]
184         if {[info exists notes($vid)]} {
185             errexpect-error "duplicate vesselid $vid"
186         }
187         set notes($vid) [list $lno $vname $owner $note]
188     }
189 }
190
191 proc note-info {lno vid name island description} {
192     global note_infos
193     lappend note_infos [list $lno $vid $name $island $description]
194 }
195
196 proc display-note-infos {} {
197     global note_infos note_missings notes
198
199     set nmissing [llength $note_missings]
200     debug "display-note-infos $nmissing [array size notes]"
201
202     if {[llength $note_infos]} {
203         set tiny "[llength $note_infos] warnings"
204     } elseif {$nmissing && [array size notes]} {
205         set tiny "$nmissing missing"
206     } else {
207         return
208     }
209
210     set infodata {}
211
212     foreach info $note_infos {
213         manyset $info lno vid name island description
214         append infodata "vessel"
215         append infodata " $vid"
216         if {[string length $name]} { append infodata " $name" }
217         if {[string length $island]} { append infodata " ($island)" }
218         append infodata ": " $description "\n"
219     }
220
221     if {$nmissing} {
222         if {[string length $infodata]} { append infodata "\n" }
223         append infodata "$nmissing vessel(s) not mentioned in notes:\n"
224         set last_island {}
225         foreach info [lsort $note_missings] {
226             manyset $info island name vid
227             if {[string compare $island $last_island]} {
228                 append infodata "# $island:\n"
229                 set last_island $island
230             }
231             append infodata [format "%-9d %-29s =\n" $vid $name]
232         }
233     }
234
235     parser-control-failed-core .ctrl.notes notes \
236         white blue 0 \
237         $tiny \
238         "[llength $note_infos] warning(s);\
239          $nmissing vessel(s) missing" \
240         "Full description of warnings and missing vessels:" \
241         $infodata
242 }
243
244 #---------- vessel properties ----------
245
246 proc vesselclasses-init {} {
247     global vc_game2code vc_code2abbrev vc_abbrev2full
248     foreach {game code abbrev full} {
249         smsloop         am      sl      Sloop
250         lgsloop         bm      ct      Cutter
251         dhow            cm      dh      Dhow
252         longship        dm      ls      Longship
253         baghlah         em      bg      Baghlah
254         merchbrig       fm      mb      {Merchant Brig}
255         warbrig         gm      wb      {War Brig}
256         xebec           hm      xe      Xebec
257         warfrig         im      wf      {War Frigate}
258         merchgal        jm      mg      {Merchant Galleon}
259         grandfrig       km      gf      {Grand Frigate}
260     } {
261         set vc_game2code($game) $code
262         set vc_code2abbrev($code) $abbrev
263         set vc_abbrev2full($abbrev) $full
264     }
265 }
266
267 proc code2abbrev {code} {
268     global vc_code2abbrev
269
270     manyset [split $code _] inport class subclass lockown xabbrev
271     manyset [split $lockown ""] lock own
272
273     set abbrev {}
274     append abbrev [lindex {? {}} $inport]
275     append abbrev $vc_code2abbrev($class)
276     append abbrev $subclass
277     append abbrev [lindex {* + -} $lock]
278     append abbrev [lindex {- = ?} [regsub {\D} $own 2]]
279     append abbrev $xabbrev
280
281     debug "CODE2ABBREV $code $abbrev"
282     return $abbrev
283 }
284     
285 #---------- loading and parsing the clipboard (vessel locations) ----------
286
287 proc vessel {vin} {
288     global pirate notes_used note_missings newnotes
289     upvar 1 $vin vi
290
291     set codel {}
292     lappend codel [errexpect-arrayget-boolean vi inPort]
293
294     set gameclass [errexpect-arrayget vi vesselClass]
295     upvar #0 vc_game2code($gameclass) class
296     if {![info exists class]} { errexpect-error "unexpected vesselClass"}
297     lappend codel $class
298
299     set subclass [errexpect-arrayget vi vesselSubclass]
300     switch -exact $subclass {
301         null            { lappend codel {} }
302         icy             { lappend codel F }
303         default         { lappend codel ($subclass) }
304     }
305
306     switch -exact [errexpect-arrayget vi isLocked]/[ \
307                    errexpect-arrayget vi isBattleReady] {
308         true/false      { set lock 2 }
309         false/false     { set lock 1 }
310         false/true      { set lock 0 }
311         default         { errexpect-error "unexpected isLocked/isBattleReady" }
312     }
313
314     set vid [errexpect-arrayget vi vesselId]
315     upvar #0 notes($vid) note
316     set realname [errexpect-arrayget vi vesselName]
317     set island [errexpect-arrayget vi islandName]
318
319     set owner {}
320     set xabbrev {}
321     if {[info exists note]} {
322         manyset $note lno notename owner xabbrev
323         if {[string compare -nocase $realname $notename]} {
324             note-info $lno $vid $realname $island \
325                 "notes say name is $notename"
326         }
327         if {[string length $owner]} {
328             if {![string compare $owner $pirate]} {
329                 set own 1
330             } else {
331                 set own 0
332             }
333         } else {
334             set own U
335         }
336         append abbrev $xabbrev
337         set notes_used($vid) 1
338
339     } else {
340         set own M
341         lappend note_missings [list $island $realname $vid]
342     }
343
344     lappend codel "$lock$own" $xabbrev
345     lappend newnotes [list $vid $realname $owner $xabbrev]
346     set kk "$island [join $codel _]"
347     upvar #0 count($kk) k
348     if {![info exists k]} { set k 0 }
349     incr k
350
351     debug "CODED $kk $vid $realname"
352 }
353
354 set clipboard {}
355 proc parse-clipboard {} {
356     global clipboard count notes notes_used newnotes
357
358     catch { unset count }
359     catch { unset notes_used }
360     glset note_infos {}
361     glset note_missings {}
362
363     set newnotes {}
364     
365     set itemre { (\w+) = ([^=]*) }
366     set manyitemre "^\\\[ $itemre ( (?: ,\\ $itemre)* ) \\]\$"
367     debug $manyitemre
368
369     set lno 0
370     foreach l [split $clipboard "\n"] {
371         incr lno
372         errexpect-setline $lno $l
373         if {![string length $l]} continue
374         catch { unset vi }
375         while 1 {
376                 if {![regexp -expanded $manyitemre $l dummy \
377                         thiskey thisval rhs]} {
378                     errexpect-error "badly formatted"
379                 }
380                 set vi($thiskey) $thisval
381                 if {![string length $rhs]} break
382                 regsub {^, } $rhs {} rhs
383                 set l "\[$rhs\]"
384         }
385         vessel vi
386     }
387
388     if {[llength $newnotes]} {
389         foreach vid [lsort [array names notes]] {
390             if {![info exists notes_used($vid)]} {
391                 manyset $notes($vid) lno notename
392                 note-info $lno $vid $notename {} \
393                     "vessel in notes no longer found"
394             }
395         }
396     }
397 }
398
399 proc load-clipboard-file {fn} {
400     set f [open $fn]
401     glset clipboard [read $f]
402     close $f
403 }
404
405
406 #---------- loading and parsing the chart ----------
407
408 proc load-chart {} {
409     global chart scraper
410     debug "FETCHING CHART"
411     set chart [eval exec $scraper [list | perl -we {
412         use strict;
413         use CommodsScrape;
414         use IO::File;
415         use IO::Handle;
416         yppedia_chart_parse(\*STDIN, (new IO::File ">/dev/null"),
417                 sub { sprintf "%d %d", @_; },
418                 sub { printf "archlabel %d %d %s\n", @_; },
419                 sub { printf "island %s %s\n", @_; },
420                 sub { printf "league %s %s %s.\n", @_; },
421                 sub { printf STDERR "warning: %s: incomprehensible: %s", @_; }
422                         );
423         STDOUT->error and die $!;
424     }]]
425 }
426
427
428 set scale 16
429
430 proc coord {c} {
431         global scale
432         return [expr {$c * $scale}]
433 }
434
435 proc chart-got/archlabel {args} { }
436 proc chart-got/island {x y args} {
437 #       debug "ISLE $x $y $args"
438         global canvas isleloc
439         set isleloc($args) [list $x $y]
440         set sz 5
441 #       $canvas create oval \
442 #               [expr {[coord $x] - $sz}] [expr {[coord $y] - $sz}] \
443 #               [expr {[coord $x] + $sz}] [expr {[coord $y] + $sz}] \
444 #               -fill blue
445         $canvas create text [coord $x] [coord $y] \
446                 -text $args -anchor s
447 }
448 proc chart-got/league {x1 y1 x2 y2 kind} {
449 #       debug "LEAGUE $x1 $y1 $x2 $y2 $kind"
450         global canvas
451         set l [$canvas create line \
452                 [coord $x1] [coord $y1] \
453                 [coord $x2] [coord $y2]]
454         if {![string compare $kind .]} {
455                 $canvas itemconfigure $l -dash .
456         }
457 }
458
459 proc draw {} {
460     global chart count isleloc canvas
461     
462     $canvas delete all
463
464     foreach l [split $chart "\n"] {
465 #       debug "CHART-GOT $l"
466         set proc [lindex $l 0]
467         eval chart-got/$proc [lrange $l 1 end]
468     }
469
470     set lastislandname {}
471     foreach key [lsort [array names count]] {
472         set c $count($key)
473 #       debug "SHOWING $key $c"
474         regexp {^(.*) (\S+)$} $key dummy islandname code
475
476         set abbrev [code2abbrev $code]
477         
478         if {[string compare $lastislandname $islandname]} {
479                 manyset $isleloc($islandname) x y
480                 set x [coord $x]
481                 set y [coord $y]
482                 set lastislandname $islandname
483 #               debug "START Y $y"
484         }
485         set text $abbrev
486         regsub -all {[0-9]} $text {} text
487         if {$c > 1} {
488                 set text [format "%2d%s" $c $text]
489         } else {
490                 set text [format "  %s" $text]
491         }
492         set id [$canvas create text $x $y \
493                 -anchor nw -font fixed \
494                 -text $text]
495         set bbox [$canvas bbox $id]
496         set bid [eval $canvas create rectangle $bbox -fill white]
497         $canvas lower $bid $id
498         manyset $bbox dummy dummy dummy y
499 #       debug "NEW Y $y"
500     }
501
502     panner::updatecanvas-bbox .ctrl.pan
503 }
504
505
506 #---------- parser error reporting ----------
507
508 proc parser-control-create {w base invokebuttontext etl_title} {
509     frame $w
510     button $w.do -text $invokebuttontext -command invoke_$base
511
512     frame $w.resframe -width 120 -height 32
513     button $w.resframe.res -text {} -anchor nw \
514         -padx 1 -pady 1 -borderwidth 0 -justify left
515     glset deffont_$base [$w.resframe.res cget -font]
516     place $w.resframe.res -relx 0.5 -y 0 -anchor n
517
518     pack $w.do -side top
519     pack $w.resframe -side top -expand y -fill both
520
521     set eb .err_$base
522     toplevel $eb
523     wm withdraw $eb
524     wm title $eb "where-vessels - $etl_title"
525
526     label $eb.title -text $etl_title
527     pack $eb.title -side top
528
529     button $eb.close -text Close -command [list wm withdraw $eb]
530     pack $eb.close -side bottom
531
532     frame $eb.emsg -bd 2 -relief groove
533     label $eb.emsg.lab -text "Error:"
534     text $eb.emsg.text -height 1
535     pack $eb.emsg.text -side bottom
536     pack $eb.emsg.lab -side left
537
538     pack $eb.emsg -side top -pady 2
539
540     frame $eb.text -bd 2 -relief groove
541     pack $eb.text -side bottom -pady 2
542     
543     label $eb.text.lab
544
545     text $eb.text.text -width 85 \
546         -xscrollcommand [list $eb.text.xscroll set] \
547         -yscrollcommand [list $eb.text.yscroll set]
548     $eb.text.text tag configure error \
549         -background red -foreground white
550
551     scrollbar $eb.text.xscroll -orient horizontal \
552         -command [list $eb.text.text xview]
553     scrollbar $eb.text.yscroll -orient vertical \
554         -command [list $eb.text.text yview]
555
556     grid configure $eb.text.lab -row 0 -column 0 -sticky w
557     grid configure $eb.text.text -row 1 -column 0
558     grid configure $eb.text.yscroll -sticky ns -row 1 -column 1
559     grid configure $eb.text.xscroll -sticky ew -row 2 -column 0
560 }
561
562 proc parser-control-ok-core {w base background show} {
563     debug "parser-control-ok-core $w $base $background $show"
564     upvar #0 deffont_$base deffont
565     $w.resframe.res configure \
566         -background $background -disabledforeground black -font $deffont \
567         -state disabled -command {} \
568         -text $show
569 }    
570 proc parser-control-ok {w base show} {
571     parser-control-ok-core $w $base green $show
572 }
573 proc parser-control-none {w base show} {
574     parser-control-ok-core $w $base blue $show
575 }
576 proc parser-control-failed-core {w base foreground background smallfont
577                                  tiny summary fulldesc fulldata} {
578     debug "parser-control-failed-core $w $base $summary $fulldesc"
579     upvar #0 deffont_$base deffont
580     set eb .err_$base
581
582     $eb.emsg.text delete 0.0 end
583     $eb.emsg.text insert end $summary
584
585     $eb.text.lab configure -text $fulldesc
586     $eb.text.text delete 0.0 end
587     $eb.text.text insert end $fulldata
588
589     regsub -all {.{18}} $tiny "&\n" ewrap
590
591     if {$smallfont} {
592         set font fixed
593     } else {
594         set font $deffont
595     }
596
597     $w.resframe.res configure \
598         -background $background -foreground $foreground -font $font \
599         -state normal -command [list wm deiconify $eb] \
600         -text $ewrap
601 }
602     
603 proc parser-control-failed-expected {w base emsg lno ei fulldesc newdata} {
604     set eb .err_$base
605
606     set line [lindex [split $ei "\n"] 0]
607     debug "parser-control-failed-expected: $w $base: $lno: $emsg\n $line"
608
609     parser-control-failed-core $w $base \
610         white red 1 \
611         "err: [string trim $emsg]: \"$line\"" \
612         "at line $lno: $emsg" \
613         $fulldesc $newdata
614
615     $eb.text.text tag add error $lno.0 $lno.end
616     $eb.text.text see $lno.0    
617 }
618 proc parser-control-failed-unexpected {w base emsg ei} {
619     global errorInfo
620     parser-control-failed-core $w $base \
621         black yellow 1 \
622         $emsg $emsg "Details and stack trace:" $ei
623 }
624
625 proc reparse {base varname old fulldesc okshow noneshow parse ok} {
626     upvar #0 $varname var
627     manyset [errexpect-catch {
628         uplevel 1 $parse
629         if {[string length [string trim $var]]} {
630             parser-control-ok .ctrl.$base $base $okshow
631         } else {
632             parser-control-none .ctrl.$base $base $noneshow
633         }
634     }] failed emsg lno ei
635     if {$failed} {
636         parser-control-failed-expected .ctrl.$base $base \
637             $emsg $lno $ei $fulldesc $var
638         set var $old
639         uplevel 1 $parse
640     } else {
641         uplevel 1 $ok
642     }
643 }
644
645 #---------- main user interface ----------
646
647 proc widgets-setup {} {
648     global canvas debug pirate ocean
649
650     frame .f -border 1 -relief groove
651     set canvas .f.c
652     canvas $canvas
653     pack $canvas -expand 1 -fill both
654     pack .f -expand 1 -fill both -side left
655
656     frame .ctrl
657     pack .ctrl -side right
658
659     debug "BBOX [$canvas bbox all]"
660
661     panner::canvas-scroll-bbox .f.c
662     panner::create .ctrl.pan .f.c 120 120 $debug
663
664     pack .ctrl.pan -side top -pady 10 -padx 5
665     frame .ctrl.zoom
666     pack .ctrl.zoom -side top
667
668     button .ctrl.zoom.out -text - -font {Courier 16} -command {zoom /2}
669     button .ctrl.zoom.in  -text + -font {Courier 16} -command {zoom *2}
670     pack .ctrl.zoom.out .ctrl.zoom.in -side left
671
672     parser-control-create .ctrl.acquire \
673         acquire Acquire \
674         "Clipboard parsing error" \
675         
676     pack .ctrl.acquire -side top -pady 2
677
678     parser-control-create .ctrl.notes \
679         notes "Reload notes" \
680         "Vessel notes loading report" \
681         
682     pack .ctrl.notes -side top -pady 2
683
684     wm geometry . 1024x480
685     wm title . "where-vessels - $pirate on the $ocean ocean"
686 }
687
688 proc zoom {extail} {
689     global scale canvas
690     set nscale [expr "\$scale $extail"]
691     debug "ZOOM $scale $nscale"
692     if {$nscale < 1 || $nscale > 200} return
693     set scale $nscale
694     draw
695 }
696
697 proc invoke_acquire {} {
698     global clipboard errorInfo
699     set old $clipboard
700
701     if {[catch {
702         set clipboard [clipboard get]
703     } emsg]} {
704         parser-control-failed-unexpected .ctrl.acquire acquire \
705             $emsg "fetching clipboard:\n\n$errorInfo"
706         return
707     }
708
709     reparse acquire \
710         clipboard $old "Clipboard contents:" { acquired ok } { no vessels } {
711             parse-clipboard
712         } {
713             display-note-infos
714         }
715     draw
716 }
717
718 proc invoke_notes {} {
719     global notes_data errorInfo notes_loc
720     set old $notes_data
721     
722     if {[catch {
723         load-notes
724     } emsg]} {
725         parser-control-failed-unexpected .ctrl.notes notes \
726             $emsg "loading $notes_loc:\n\n$errorInfo"
727         return
728     }
729
730     reparse notes \
731         notes_data $old "Vessel notes:" "loaded ok" { no notes } {
732             parse-notes
733             parse-clipboard
734         } {
735             display-note-infos
736         }
737     draw
738 }
739
740 #---------- main program ----------
741
742 vesselclasses-init
743
744 parseargs
745 argdefaults
746 httpclientsetup where-vessels
747 load-chart
748 widgets-setup
749
750 set notes_data {}
751 if {[catch { parse-clipboard } emsg]} {
752     puts stderr "$emsg\n$errorInfo"
753     exit 1
754 }
755 after idle invoke_notes
756
757 draw