chiark / gitweb /
061d5db48f163837779ee0cf8fb6ba1c8f4d299b
[ypp-sc-tools.main.git] / yarrg / where-vessels
1 #!/usr/bin/wish
2 # show your vessels on a map
3
4 # This is part of ypp-sc-tools, a set of third-party tools for assisting
5 # players of Yohoho Puzzle Pirates.
6 #
7 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
8 #
9 # This program is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 #
22 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
23 # are used without permission.  This program is not endorsed or
24 # sponsored by Three Rings.
25
26
27
28 source yarrglib.tcl
29 source panner.tcl
30 package require http
31
32 #---------- general utilities ----------
33
34 set debug 0
35 proc debug {m} {
36     global debug
37     if {$debug} { puts "DEBUG $m" }
38 }
39
40 proc badusage {m} {
41     puts stderr "where-vessels: bad usage: $m"
42     exit 1
43 }
44
45 proc glset {n val} {
46     upvar #0 $n var
47     set var $val
48 }
49
50 #---------- expecting certain errors ----------
51
52 proc errexpect-setline {lno line} {
53     glset errexpect_lno $lno
54     glset errexpect_line $line
55 }
56
57 proc errexpect-error {m} {
58     global errexpect_line errexpect_lno
59     error $m "$errexpect_line\n" [list YARRG-ERREXPECT $errexpect_lno]
60 }
61
62 proc errexpect-arrayget {arrayvar key} {
63     upvar 1 $arrayvar av
64     debug "VARS [array names av]"
65     upvar 1 ${arrayvar}($key) v
66     if {[info exists v]} { return $v }
67     errexpect-error "undefined $key"
68 }
69
70 proc errexpect-catch {code} {
71     global errorInfo errorCode
72     set rc [catch {
73         uplevel 1 $code
74     } rv]
75     debug "ERREXPECT CATCH |$rc|$rv|$errorCode|$errorInfo|"
76     if {$rc==1 && ![string compare YARRG-ERREXPECT [lindex $errorCode 0]]} {
77         return [list 1 $rv [lindex $errorCode 1] $errorInfo]
78     } elseif {$rc==0} {
79         return [list 0 $rv]
80     } else {
81         return -code $rc -errorinfo $errorInfo -errorcode $errorCode $rv
82     }
83 }
84
85 #---------- argument parsing ----------
86
87 proc nextarg {} {
88     global ai argv
89     if {$ai >= [llength $argv]} {
90         badusage "option [lindex $argv [expr {$ai-1}]] needs a value"
91     }
92     set v [lindex $argv $ai]
93     incr ai
94     return $v
95 }
96
97 set notes_loc vessel-notes
98 set scraper {./yppedia-ocean-scraper --chart}
99
100 proc parseargs {} {
101     global ai argv
102     global debug scraper
103     set ai 0
104
105     while {[regexp {^\-} [set arg [lindex $argv $ai]]]} {
106         incr ai
107         switch -exact -- $arg {
108             -- { break }
109             --pirate { glset pirate [string totitle [nextarg]] }
110             --ocean { glset ocean [string totitle [nextarg]] }
111             --clipboard-file { load-clipboard-file [nextarg] }
112             --local-html-dir { lappend scraper --local-html-dir=[nextarg] }
113             --notes { glset notes_loc [nextarg] }
114             --debug { incr debug }
115             default { badusage "unknown option $arg" }
116         }
117     }
118     set argv [lrange $argv $ai end]
119     if {[llength $argv]} { badusage "non-option args not allowed" }
120 }
121
122 proc argdefaults {} {
123     global ocean notes_loc pirate scraper
124     if {![info exists ocean] || ![info exists pirate]} {
125         set cmd {./yarrg --find-window-only --quiet}
126         if {[info exists ocean]} { lappend cmd --ocean $ocean }
127         if {[info exists pirate]} { lappend cmd --pirate $pirate }
128         manyset [split [eval exec $cmd] " "] ocean pirate
129     }
130     lappend scraper $ocean
131 }
132
133
134 #---------- loading and parsing the vessel notes ----------
135
136 proc load-notes {} {
137     global notes_loc notes
138     catch { unset notes }
139     if {[regexp {^\w+\:} $notes_loc]} {
140         vwait idletasks
141         debug "FETCHING NOTES"
142         ::http::geturl $notes_loc
143         switch -glob [::http::status].[::http::ncode] {
144             ok.200 { }
145             ok.* { error "retrieving vessel-notes $url: [::http::code]" }
146             * { error "retrieving vessel-notes $url: [::http::error]" }
147         }
148         set notes_data [::http::data]
149         ::http::cleanup
150     } else {
151         set vn [open $notes_loc]
152         set notes_data [read $vn]
153         close $vn
154     }
155     foreach l [split $notes_data "\n"] {
156         regsub -all {\t+} $l "\t" l
157         manyset [split $l "\t"] vname vid owner note
158         set nk $vid.$vname
159         debug "SET NOTE $nk"
160         set notes($nk) [list $owner $note]
161     }
162 }
163
164
165 #---------- loading and parsing the clipboard (vessel locations) ----------
166
167 proc vessel {vin} {
168     global pirate notes_used
169     upvar 1 $vin vi
170     switch -exact [errexpect-arrayget vi vesselClass] {
171         smsloop         { set sz 00sl }
172         lgsloop         { set sz 01ct }
173         dhow            { set sz 02dh }
174         longship        { set sz 03ls }
175         baghlah         { set sz 04bg }
176         merchbrig       { set sz 05mb }
177         warbrig         { set sz 06wb }
178         xebec           { set sz 07xe }
179         warfrig         { set sz 08wf }
180         merchgal        { set sz 09mg }
181         grandfrig       { set sz 10gf }
182         default         { errexpect-error "unknown class" }
183     }
184     set abbrev $sz
185     switch -exact [errexpect-arrayget vi vesselSubclass] {
186         null            { }
187         icy             { append abbrev F }
188         default         { errexpect-error "unknown subclass ?" }
189     }
190     switch -exact [errexpect-arrayget vi isLocked]/[ \
191                    errexpect-arrayget vi isBattleReady] {
192         true/false      { append abbrev 2- }
193         false/false     { append abbrev 1+ }
194         false/true      { append abbrev 0* }
195         default         { errexpect-error "unexpected isLocked/isBattleReady" }
196     }
197     switch -exact [errexpect-arrayget vi inPort] {
198         true            { }
199         false           { append abbrev ? }
200         default         { errexpect-error "unexpected inPort" }
201     }
202     set nk [errexpect-arrayget vi vesselId].[errexpect-arrayget vi vesselName]
203     upvar #0 notes($nk) note
204     if {[info exists note]} {
205         manyset $note owner xabbrev
206         if {![string compare $owner $pirate]} {
207             append abbrev =
208         } else {
209             append abbrev -
210         }
211         append abbrev $xabbrev
212         set notes_used($nk) 1
213     } else {
214         debug "UNKNOWN $nk"
215     }
216     set kk "[errexpect-arrayget vi islandName] $abbrev"
217     upvar #0 count($kk) k
218     if {![info exists k]} { set k 0 }
219     incr k
220 }
221
222 set clipboard {}
223 proc parse-clipboard {} {
224     global clipboard count notes notes_used
225
226     catch { unset count }
227     catch { unset notes_used }
228     
229     set itemre { (\w+) = ([^=]*) }
230     set manyitemre "^\\\[ $itemre ( (?: ,\\ $itemre)* ) \\]\$"
231     debug $manyitemre
232
233     set lno 0
234     foreach l [split $clipboard "\n"] {
235         incr lno
236         errexpect-setline $lno $l
237         if {![string length $l]} continue
238         catch { unset vi }
239         while 1 {
240                 if {![regexp -expanded $manyitemre $l dummy \
241                         thiskey thisval rhs]} {
242                     errexpect-error "badly formatted"
243                 }
244                 set vi($thiskey) $thisval
245                 if {![string length $rhs]} break
246                 regsub {^, } $rhs {} rhs
247                 set l "\[$rhs\]"
248         }
249         vessel vi
250     }
251
252     foreach nk [lsort [array names notes]] {
253         if {![info exists notes_used($nk)]} {
254             debug "IGNORED NOTE $nk"
255         }
256     }
257 }
258
259 proc load-clipboard-file {fn} {
260     set f [open $fn]
261     glset clipboard [read $f]
262     close $f
263 }
264
265
266 #---------- loading and parsing the chart ----------
267
268 proc load-chart {} {
269     global chart scraper
270     debug "FETCHING CHART"
271     set chart [eval exec $scraper [list | perl -we {
272         use strict;
273         use CommodsScrape;
274         use IO::File;
275         use IO::Handle;
276         yppedia_chart_parse(\*STDIN, (new IO::File ">/dev/null"),
277                 sub { sprintf "%d %d", @_; },
278                 sub { printf "archlabel %d %d %s\n", @_; },
279                 sub { printf "island %s %s\n", @_; },
280                 sub { printf "league %s %s %s.\n", @_; },
281                 sub { printf STDERR "warning: %s: incomprehensible: %s", @_; }
282                         );
283         STDOUT->error and die $!;
284     }]]
285 }
286
287
288 set scale 16
289
290 proc coord {c} {
291         global scale
292         return [expr {$c * $scale}]
293 }
294
295 proc chart-got/archlabel {args} { }
296 proc chart-got/island {x y args} {
297 #       debug "ISLE $x $y $args"
298         global canvas isleloc
299         set isleloc($args) [list $x $y]
300         set sz 5
301 #       $canvas create oval \
302 #               [expr {[coord $x] - $sz}] [expr {[coord $y] - $sz}] \
303 #               [expr {[coord $x] + $sz}] [expr {[coord $y] + $sz}] \
304 #               -fill blue
305         $canvas create text [coord $x] [coord $y] \
306                 -text $args -anchor s
307 }
308 proc chart-got/league {x1 y1 x2 y2 kind} {
309 #       debug "LEAGUE $x1 $y1 $x2 $y2 $kind"
310         global canvas
311         set l [$canvas create line \
312                 [coord $x1] [coord $y1] \
313                 [coord $x2] [coord $y2]]
314         if {![string compare $kind .]} {
315                 $canvas itemconfigure $l -dash .
316         }
317 }
318
319 proc draw {} {
320     global chart count isleloc canvas
321     
322     $canvas delete all
323
324     foreach l [split $chart "\n"] {
325 #       debug "CHART-GOT $l"
326         set proc [lindex $l 0]
327         eval chart-got/$proc [lrange $l 1 end]
328     }
329
330     set lastislandname {}
331     foreach key [lsort [array names count]] {
332         set c $count($key)
333 #       debug "SHOWING $key $c"
334         regexp {^(.*) (\S+)$} $key dummy islandname abbrev
335         if {[string compare $lastislandname $islandname]} {
336                 manyset $isleloc($islandname) x y
337                 set x [coord $x]
338                 set y [coord $y]
339                 set lastislandname $islandname
340 #               debug "START Y $y"
341         }
342         set text $abbrev
343         regsub -all {[0-9]} $text {} text
344         if {$c > 1} {
345                 set text [format "%2d%s" $c $text]
346         } else {
347                 set text [format "  %s" $text]
348         }
349         set id [$canvas create text $x $y \
350                 -anchor nw -font fixed \
351                 -text $text]
352         set bbox [$canvas bbox $id]
353         set bid [eval $canvas create rectangle $bbox -fill white]
354         $canvas lower $bid $id
355         manyset $bbox dummy dummy dummy y
356 #       debug "NEW Y $y"
357     }
358
359     panner::updatecanvas-bbox .ctrl.pan
360 }
361
362
363 #---------- user interface ----------
364
365 proc widgets-setup {} {
366     global canvas debug acqdeffont
367
368     frame .f -border 1 -relief groove
369     set canvas .f.c
370     canvas $canvas
371     pack $canvas -expand 1 -fill both
372     pack .f -expand 1 -fill both -side left
373
374     frame .ctrl
375     pack .ctrl -side right
376
377     debug "BBOX [$canvas bbox all]"
378
379     panner::canvas-scroll-bbox .f.c
380     panner::create .ctrl.pan .f.c 120 120 $debug
381
382     pack .ctrl.pan -side top -pady 10 -padx 5
383     frame .ctrl.zoom
384     pack .ctrl.zoom -side top
385
386     button .ctrl.zoom.out -text - -font {Courier 16} -command {zoom /2}
387     button .ctrl.zoom.in  -text + -font {Courier 16} -command {zoom *2}
388     pack .ctrl.zoom.out .ctrl.zoom.in -side left
389
390     frame .ctrl.acquire
391     button .ctrl.acquire.do -text Acquire -command acquire
392
393     frame .ctrl.acquire.resframe -width 120 -height 32
394     button .ctrl.acquire.resframe.res -text {} -anchor nw \
395         -padx 1 -pady 1 -borderwidth 0 -justify left
396     glset acqdeffont [.ctrl.acquire.resframe.res cget -font]
397     place .ctrl.acquire.resframe.res -relx 0.5 -y 0 -anchor n
398     #   -relheight 1.0 -relwidth 1.0
399
400     pack .ctrl.acquire.do -side top
401     pack .ctrl.acquire.resframe -side top -expand y -fill both
402     pack .ctrl.acquire -side top
403
404     toplevel .err_acquire
405     wm withdraw .err_acquire
406     wm title .err_acquire "where-vessels clipboard parsing error"
407
408     label .err_acquire.title -text "Clipboard parsing error"
409     pack .err_acquire.title -side top
410
411     button .err_acquire.close -text Close -command {wm withdraw .err_acquire}
412     pack .err_acquire.close -side bottom
413
414     frame .err_acquire.emsg -bd 2 -relief groove
415     label .err_acquire.emsg.lab -text "Error:"
416     text .err_acquire.emsg.text -height 1
417     pack .err_acquire.emsg.text -side bottom
418     pack .err_acquire.emsg.lab -side left
419
420     pack .err_acquire.emsg -side top -pady 2
421
422     frame .err_acquire.text -bd 2 -relief groove
423     pack .err_acquire.text -side bottom -pady 2
424     
425     label .err_acquire.text.lab -text "Clipboard contents:"
426
427     text .err_acquire.text.text \
428         -xscrollcommand {.err_acquire.text.xscroll set} \
429         -yscrollcommand {.err_acquire.text.yscroll set}
430
431     scrollbar .err_acquire.text.xscroll -orient horizontal \
432         -command {.err_acquire.text.text xview}
433     scrollbar .err_acquire.text.yscroll -orient vertical \
434         -command {.err_acquire.text.text yview}
435
436     grid configure .err_acquire.text.lab -row 0 -column 0 -sticky w
437     grid configure .err_acquire.text.text -row 1 -column 0
438     grid configure .err_acquire.text.yscroll -sticky ns -row 1 -column 1
439     grid configure .err_acquire.text.xscroll -sticky ew -row 2 -column 0
440
441     wm geometry . 1024x480
442 }
443
444 proc zoom {extail} {
445     global scale canvas
446     set nscale [expr "\$scale $extail"]
447     debug "ZOOM $scale $nscale"
448     if {$nscale < 1 || $nscale > 200} return
449     set scale $nscale
450     draw
451 }
452
453 proc acquire_showerror {} {
454     global acqerr
455     tk_messageBox -type ok \
456         -title "where-vessels: clipboard parsing error" \
457         -message $acqerr
458 }
459
460 proc acquire {} {
461     global clipboard acqdeffont acqerr errorInfo
462     set old $clipboard
463     set nclipboard [clipboard get]
464     manyset [errexpect-catch {
465         set clipboard $nclipboard
466         parse-clipboard
467         .ctrl.acquire.resframe.res configure \
468             -background blue -disabledforeground black -font $acqdeffont \
469             -state disabled -command {} \
470             -text " acquired ok "
471     }] failed emsg lno ei
472     if {$failed} {
473         set line [lindex [split $ei "\n"] 0]
474         puts stderr "clipboard parsing failed: line $lno: $emsg\n $line"
475         regsub -all {.{18}} "bad: [string trim $emsg]: \"$line\"" "&\n" ewrap
476
477         .err_acquire.emsg.text delete 0.0 end
478         .err_acquire.emsg.text insert end "at line $lno: $emsg"
479
480         .err_acquire.text.text delete 0.0 end
481         .err_acquire.text.text insert end $nclipboard
482
483         .err_acquire.text.text tag add error $lno.0 $lno.end
484         .err_acquire.text.text tag configure error \
485             -background red -foreground white
486         .err_acquire.text.text see $lno.0       
487         
488         .ctrl.acquire.resframe.res configure \
489             -background red -foreground white -font fixed \
490             -state normal -command {wm deiconify .err_acquire} \
491             -text $ewrap
492         set clipboard $old
493         parse-clipboard
494     }
495     draw
496 }
497
498
499 #---------- main program ----------
500
501 parseargs
502 argdefaults
503 httpclientsetup where-vessels
504 load-chart
505 widgets-setup
506
507 load-notes
508 parse-clipboard
509
510 draw