#!/usr/bin/env python ''' trackplacer -- map journey track editor. usage: trackplacer [-vh?] [filename] If the filename is not specified, trackplacer will enter a loop in which it repeatedly pops up a file selector. Canceling the file selecct ends the program; Selecting a file takes you to a main screen. For command help on the main screen, click the Help button. Can be started with a map image, in which case we are editing a new journey. Can be started with a .cfg file. All parts of .cfg files other than the NEW_* macros placing tracking icons are ignored, except that a comment of the form "# trackplacer: map=fubar.png" is interpreted as a declaration that this track has the base map fubar.png (or similarly for any other fiilrename after the = sign). The NEW_* macros are interpreted snd their features appended to the track in the order they are given in the file. A journey is an object containing a map file name and a (possibly empty) track. This program exists to visually edit journeys represented in .cfg files. Normally, trackplacer assumes it is running within a Battle for Wesnoth source tree and changes directory to the root of the tree. Paths saved in track files are relative to the tree root. All pathnames in help and error messages are also relativized to that root. The -v option enables verbose logging to standard error. The -d option sets the root directory to use. The -h or -? options display this summary. ''' gui_help = '''\ This is trackplacer, an editor for visually editing journey tracks on Battle For Wesnoth maps. The radio buttons near the top left corner control which icon is placed by a left click, except that the when the trashcan is selected a left click deletes already-placed icons. The Animate button clears the icons off the map and places them with a delay after each placement, so you can see what order they are drawn in. The Save button pops up a file selector asking you to supply a filename to which the track should be saved in .cfg format, as a series of macros suitable for inclusion in WML. Any other extension than .cfg on the filename will raise an error. The rule for adding markers to the track is as follows: if the two markers closest to the mouse pointer are adjacent on the track, insert the new marker between them in the track order. Otherwise, append it to the end of the track. The Help button displays this message. The Quit button ends your session, asking for confirmation if you have unsaved changes. Design and implementation by Eric S. Raymond, October 2008. ''' import sys, os, re, math, time, exceptions, getopt import pygtk pygtk.require('2.0') import gtk import wesnoth.wmltools # All dependencies on the shape of the data tree live here # The code does no semantic interpretation of these icons at all; # to add new ones, just fill in a dictionary entry. imagedir = "data/core/images/" default_map = imagedir + "maps/wesnoth.png" icon_dictionary = { "JOURNEY": imagedir + "misc/new-journey.png", "BATTLE": imagedir + "misc/new-battle.png", "REST": imagedir + "misc/flag-red.png", } icon_presentation_order = ("JOURNEY", "BATTLE", "REST") segmenters = ("BATTLE","REST") class IOException(exceptions.Exception): "Exception thrown while reading a track file." def __init__(self, message, path, lineno=None): self.message = message self.path = path self.lineno = lineno # Basic functions for bashing points and rectangles def distance(x1, y1, x2, y2): "Euclidean distance." return math.sqrt((x1 - x2)**2 + abs(y1 - y2)**2) def within(x, y, (l, t, r, d)): "Is point within specified rectangle?" if x >= l and x < l + r and y >= t and y < t + d: return True return False def overlaps((x, y, xd, yd), rect): "Do two rectangles overlap?" return within(x, y, rect) or within(x+xd-1, y, rect) or \ within(x, y+yd-1, rect) or within(x+xd-1, y+yd+1, rect) class JourneyTrack: "Represent a journey track on a map." def __init__(self): self.mapfile = None # Map background of the journey self.track = [] # List of (action, x, y) tuples self.modifications = 0 self.initial_track = [] def write(self, fp, prefix="JOURNEY_"): "Record a journey track." if fp.name.endswith(".cfg"): fp.write("# Edited by trackplacer on %s.\n"%time.ctime(time.time())) fp.write("# Hand-hack strictly at your own risk\n") fp.write("#\n") fp.write("# trackplacer: map=%s\n" % self.mapfile) fp.write("#\n") index_tuples = zip(range(len(self.track)), self.track) index_tuples = filter(lambda (i, (a, x, y)): a in segmenters, index_tuples) endpoints = map(lambda (i, t): i, index_tuples) if self.track[-1][0] not in segmenters: endpoints.append(len(self.track)-1) for (i, e) in enumerate(endpoints): fp.write("#define %sSTAGE_%d\n" % (prefix, i+1,)) for j in range(0, e+1): age="OLD" if i == 0 or j > endpoints[i-1]: age = "NEW" waypoint = (age,) + tuple(self.track[j]) fp.write(" {%s_%s %d %d}\n" % waypoint) fp.write("#enddef\n\n") fp.write("#define %sCOMPLETE\n" % prefix) for j in range(len(self.track)): waypoint = self.track[j] fp.write(" {OLD_%s %d %d}\n" % tuple(waypoint)) fp.write("#enddef\n\n") fp.close() else: raise IOException("File must have a .trk or .cfg extension.", fp.name) def read(self, fp): "Initialize a journey from map and track information." if type(fp) == type(""): try: fp = open(fp) except IOError: raise IOException("Cannot read file.", fp) if self.track: raise IOException("Reading with track nonempty.", fp.name) if fp.name.endswith(".png") or fp.name.endswith(".jpg"): self.mapfile = fp.name return if not fp.name.endswith(".cfg"): raise IOException("Cannot read this filetype.", fp.name) waypoint_re = re.compile("{NEW_(" + "|".join(icon_presentation_order) + ")" \ + " +([0-9]+) +([0-9]+)}") property_re = re.compile("# *trackplacer: ([^=]+)=(.*)") self.properties = {} for line in fp: m = re.search(waypoint_re, line) if m: try: tag = m.group(1) x = int(m.group(2)) y = int(m.group(3)) self.initial_track.append((tag, x, y)) except ValueError: raise IOException("Invalid coordinate field.", fp.name, i+1) m = re.search(property_re, line) if m: self.properties[m.group(1)] = m.group(2) if "map" in self.properties: self.mapfile = self.properties['map'] else: raise IOException("Missing map declaration.", fp.name) fp.close() self.track = self.initial_track[:] def has_unsaved_changes(self): return self.track != self.initial_track def __getitem__(self, n): return self.track[n] def __setitem__(self, n, v): self.track[n] = v def neighbors(self, x, y): "Return list of neighbors, enumerated and sorted by distance." candidates = zip(range(len(self.track)), self.track) candidates.sort(lambda (i1, (a1, x1, y1)), (i2, (a2, x2, y2)): cmp(distance(x, y, x1, y1), distance(x, y, x2, y2))) return candidates def find(self, x, y): "Find all track actions at given point." candidates = [] for (i, (tag, xt, yt)) in enumerate(self.track): if x == xt and y == yt: candidates.append(i) return candidates def insert(self, (action, x, y)): "Append a feature to the track." neighbors = self.neighbors(x, y) # There are two or more markers and we're not nearest the end one if len(neighbors) >= 2 and neighbors[0][0] != len(neighbors)-1: closest = neighbors[0] next_closest = neighbors[1] # If the neighbors are adjacent, insert between them if abs(closest[0] - next_closest[0]) == 1: self.track.insert(max(closest[0], next_closest[0]), (action, x, y)) return # Otherwise, append self.track.append((action, x, y)) def remove(self, x, y): "Remove a feature from the track." found = self.find(x, y) if found: # Prefer to delete the most recent feature self.track = self.track[:found[-1]] + self.track[found[-1]+1:] def __str__(self): return self.mapfile + ": " + `self.track` class ModalFileSelector: def __init__(self, default, legend): self.default = default self.path = None # Create a new file selection widget self.filew = gtk.FileSelection(legend) self.filew.set_modal(True); self.filew.ok_button.connect("clicked", self.selection_ok) self.filew.cancel_button.connect("clicked", self.selection_canceled) if self.default: self.filew.set_filename(self.default) self.filew.run() def selection_canceled(self, widget): self.path = None self.filew.destroy() def selection_ok(self, widget): self.path = self.filew.get_filename() if self.path.startswith(os.getcwd()): self.path = self.path[len(os.getcwd())+1:] self.filew.destroy() class TrackEditorIcon: def __init__(self, action, path): self.action = action # We need an image for the toolbar... self.image = gtk.Image() self.image.set_from_file(path) # ...and a pixbuf for drawing on the map with. self.icon = gtk.gdk.pixbuf_new_from_file(path) self.icon_width = self.icon.get_width() self.icon_height = self.icon.get_height() def bounding_box(self, x, y): "Return a bounding box for this icon when centered at (x, y)." # The +1 is a slop factor allowing for even-sized icons return (x-self.icon_width/2, y-self.icon_height/2, self.icon_width+1, self.icon_height+1) class TrackEditor: def __init__(self, path=None, verbose=False): self.verbose = verbose # Initialize our info about the map and track self.journey = JourneyTrack() self.last_read = None self.journey.read(path) if path.endswith(".trk"): self.last_read = path self.log("Initial track is %s" % self.journey) self.action = "JOURNEY" self.selected = None # Backing pixmap for drawing area self.pixmap = None # Grab the map into a pixmap self.log("about to read map %s" % self.journey.mapfile) try: self.map = gtk.gdk.pixbuf_new_from_file(self.journey.mapfile) self.map_width = self.map.get_width() self.map_height = self.map.get_height() self.map = self.map.render_pixmap_and_mask()[0] except: self.fatal_error("Error while reading background map %s" % self.journey.mapfile) # Now get the icons we'll need for scribbling on the map with. self.action_dictionary = {} try: for (action, path) in icon_dictionary.items(): icon = TrackEditorIcon(action, path) self.log("%s icon has size %d, %d" % \ (action, icon.icon_width, icon.icon_height)) self.action_dictionary[action] = icon except: self.fatal_error("error while reading icons") # Window-layout time self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_name ("trackplacer") vbox = gtk.VBox(False, 0) self.window.add(vbox) vbox.show() self.window.connect("destroy", lambda w: gtk.main_quit()) tooltips = gtk.Tooltips() # FIXME: make the control box fixed-size controls = gtk.HBox() vbox.add(controls) controls.show() # The radiobutton array on the left radiobox = gtk.HBox() controls.pack_start(radiobox, expand=False, fill=False, padding=0) radiobox.show() # Fake icon-labeled buttons with liberal use of labels... basebutton = None for action in icon_presentation_order: icon = self.action_dictionary[action] button = gtk.RadioButton(basebutton) if not basebutton: button.set_active(True) basebutton = button button.connect("toggled", self.button_callback, icon.action) radiobox.pack_start(button, expand=True, fill=True, padding=0) button.show() radiobox.pack_start(icon.image, expand=False, fill=False, padding=0) icon.image.show() tooltips.set_tip(button, "Place %s events." % action.lower()) tooltips.set_tip(icon.image, "Place %s events." % action.lower()) spacer = gtk.Label(" ") radiobox.pack_start(spacer, expand=False, fill=False, padding=0) spacer.show() # The delete button and its label button = gtk.RadioButton(button) button.connect("toggled", self.button_callback, "DELETE") radiobox.pack_start(button, expand=True, fill=True, padding=0) button.show() delimage = gtk.Image() delimage.set_from_stock(gtk.STOCK_DELETE, gtk.ICON_SIZE_SMALL_TOOLBAR) radiobox.pack_start(delimage, expand=False, fill=False, padding=0) delimage.show() tooltips.set_tip(button, "Remove events.") tooltips.set_tip(delimage, "Remove events.") spacer = gtk.Label(" ") radiobox.pack_start(spacer, expand=False, fill=False, padding=0) spacer.show() # The coordinate display in the middle self.coordwin = gtk.Label() controls.pack_start(self.coordwin, expand=True, fill=False, padding=0) self.coordwin.show() # The button array on the right buttonbox = gtk.HBox() controls.pack_end(buttonbox, expand=False, fill=False, padding=0) buttonbox.show() # A quit button button = gtk.Button("Quit") buttonbox.pack_end(button, expand=False, fill=False, padding=10) button.connect_object("clicked", self.conditional_quit, self.window) tooltips.set_tip(button, "Leave this program.") button.show() # A help button button = gtk.Button("Help") buttonbox.pack_end(button, expand=False, fill=False, padding=10) button.connect_object("clicked", self.help_handler, self.window) tooltips.set_tip(button, "See a help message describing the controls.") button.show() # A save button button = gtk.Button("Save") buttonbox.pack_end(button, expand=False, fill=False, padding=10) button.connect_object("clicked", self.save_handler, self.window) tooltips.set_tip(button, "Save track in .cfg format.") button.show() # An animate button button = gtk.Button("Animate") buttonbox.pack_end(button, expand=False, fill=False, padding=10) button.connect_object("clicked", self.animate_handler, self.window) tooltips.set_tip(button, "Animate dot-drawing as in a story part.") button.show() # Create the drawing area on a viewport that scrolls if needed. # Most of the hair here is in trying to query the height # and depth of the widgets surrounding the scrolling area. # The window frame size constants are guesses; they can vary # according to your window manager's policy. They're only used # if the map is too large to fit on the screen. WINDOW_FRAME_WIDTH = 8 WINDOW_FRAME_HEIGHT = 28 screen_width = gtk.gdk.screen_width() screen_height = gtk.gdk.screen_height() self.log("Map size = (%d,%d)" % (self.map_width, self.map_height)) self.log("Screen size = (%d,%d)" % (screen_width, screen_height)) controls_width, controls_height = controls.size_request() self.log("Control box size = (%d,%d)"%(controls_width, controls_height)) x_frame_width = WINDOW_FRAME_WIDTH y_frame_width = WINDOW_FRAME_HEIGHT + controls_height # No, I don't know why the +2 is needed. Black magic.... s_w = min(screen_width -x_frame_width, self.map_width+2) s_h = min(screen_height-y_frame_width, self.map_height+2) self.log("Scroller size = (%s,%s)" % (s_w, s_h)) scroller = gtk.ScrolledWindow() scroller.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) scroller.set_size_request(s_w, s_h) self.drawing_area = gtk.DrawingArea() self.drawing_area.set_size_request(self.map_width, self.map_height) scroller.add_with_viewport(self.drawing_area) vbox.pack_start(scroller, expand=True, fill=True, padding=0) self.drawing_area.show() scroller.show() # Signals used to handle backing pixmap self.drawing_area.connect("expose_event", self.expose_event) self.drawing_area.connect("configure_event", self.configure_event) # Event signals self.drawing_area.connect("motion_notify_event", self.motion_notify_event) self.drawing_area.connect("button_press_event", self.button_press_event) self.drawing_area.connect("leave_notify_event", lambda w, e: self.coordwin.set_text("")) self.drawing_area.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK) self.window.show() gtk.main() self.log("initialization successful") def button_callback(self, widget, data=None): "Radio button callback, changes selected editing action." if widget.get_active(): self.action = data def refresh_map(self, x=0, y=0, xs=-1, ys=-1): "Refresh part of the drawing area with the appropriate map rectangle." if xs == -1: xs = self.map_width - x if ys == -1: ys = self.map_height - y self.pixmap.draw_drawable(self.default_gc, self.map, x, y, x, y, xs, ys) def box(self, (action, x, y)): "Compute the bounding box for an icon of type ACTION at X, Y." return self.action_dictionary[action].bounding_box(x, y) def snap_to(self, x, y): "Snap a location to the nearest feature whose bounding box holds it." self.log("Neighbors of %d, %d are %s" % (x, y, self.journey.neighbors(x, y))) for (i, item) in self.journey.neighbors(x, y): if within(x, y, self.box(item)): return i else: return None def neighbors(self, (action, x, y)): "Return all track items with bounding boxes overlapping this one:" rect = self.action_dictionary[action].bounding_box(x, y) return filter(lambda item: overlaps(rect, self.box(item)), self.journey.track) def erase_feature(self, widget, (action, x, y)): "Erase specified icon from the map." neighbors = self.neighbors((action, x, y)) # Erase all nearby features that might have been damaged. for (na, nx, ny) in neighbors: rect = self.box((na, nx, ny)) self.log("Erasing action=%s, dest=%s" % (na, rect)) self.refresh_map(*rect) widget.queue_draw_area(*rect) # Redraw all nearby features except what we're erasing. for (na, nx, ny) in neighbors: if x != nx and y != ny: self.log("Redrawing action=%s" % ((na, nx, ny),)) self.draw_feature(widget, (na, nx, ny)) def draw_feature(self, widget, (action, x, y)): "Draw specified icon on the map." rect = self.box((action, x, y)) self.log("Drawing action=%s, dest=%s" % (action, rect)) self.pixmap.draw_pixbuf(self.default_gc, self.action_dictionary[action].icon, 0, 0, *rect) widget.queue_draw_area(*rect) def redraw(self, widget, delay=0): "Redraw the map and tracks." self.refresh_map() for item in self.journey.track: self.draw_feature(widget, item) if delay: time.sleep(delay) self.expose_event(widget) gtk.main_iteration(False) def configure_event(self, widget, event): "Create a new backing pixmap of the appropriate size." x, y, width, height = widget.get_allocation() self.pixmap = gtk.gdk.Pixmap(widget.window, width, height) self.default_gc = self.drawing_area.get_style().fg_gc[gtk.STATE_NORMAL] self.redraw(widget) return True def expose_event(self, widget, event=None): "Redraw the screen from the backing pixmap" if event: x , y, width, height = event.area else: x, y, width, height = widget.get_allocation() widget.window.draw_drawable(self.default_gc, self.pixmap, x, y, x, y, width, height) return False def button_press_event(self, widget, event): if event.button == 1 and self.pixmap != None: x = int(event.x) y = int(event.y) self.selected = self.snap_to(x, y) # Skip the redraw in half the cases self.log("Action %s at (%d, %d): feature = %s" % (self.action, x, y, self.selected)) if (self.selected == None) and (self.action == "DELETE"): return if (self.selected != None) and (self.action != "DELETE"): return # Actual drawing and mutation of the journey track happens here if not self.selected and self.action != "DELETE": self.draw_feature(widget, (self.action, x, y)) self.journey.insert((self.action, x, y)) elif self.selected != None and self.action == "DELETE": (action, x, y) = self.journey.track[self.selected] self.log("Deletion snapped to feature %d %s" % (self.selected,(action,x,y))) self.erase_feature(widget, (action, x, y)) self.journey.remove(x, y) self.log("Track is %s" % self.journey) return True def motion_notify_event(self, widget, event): if event.is_hint: x, y, state = event.window.get_pointer() else: x = event.x y = event.y self.coordwin.set_text("(%d, %d)" % (x, y)) state = event.state # This code enables dragging icons. if state & gtk.gdk.BUTTON1_MASK and self.pixmap != None: if self.selected is not None: (action, lx, ly) = self.journey.track[self.selected] self.erase_feature(widget, (action, lx, ly)) self.journey.track[self.selected] = (action, x, y) self.draw_feature(widget, (action, x, y)) self.log("Track is %s" % self.journey) return True # # These two functions implement a civilized quit confirmation that # prompts you if you have unsaved changes # def conditional_quit(self, w): if self.journey.has_unsaved_changes(): self.quit_check = gtk.Dialog(title="Really quit?", parent=None, flags=gtk.DIALOG_MODAL, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) label = gtk.Label("Track has unsaved changes. OK to quit?") self.quit_check.vbox.pack_start(label) label.show() self.quit_check.connect("response", self.conditional_quit_handler) self.quit_check.run() else: sys.exit(0) def conditional_quit_handler(self, widget, id): if id == gtk.RESPONSE_ACCEPT: sys.exit(0) elif id == gtk.RESPONSE_REJECT: self.quit_check.destroy() def save_handler(self, w): "Save track data," if not self.journey.has_unsaved_changes(): w = gtk.MessageDialog(type=gtk.MESSAGE_INFO, flags=gtk.DIALOG_DESTROY_WITH_PARENT, buttons=gtk.BUTTONS_OK) w.set_markup("You have no unsaved changes.") w.run() w.destroy() else: w = ModalFileSelector(default=self.last_read, legend="Save track to file") if not w.path.endswith(".cfg"): raise IOException("File must have a .cfg extension.", w.path) if w.path != self.last_read and os.path.exists(w.path): self.save_check = gtk.Dialog(title="Really overwrite?", parent=None, flags=gtk.DIALOG_MODAL, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)) label = gtk.Label("Overwrite existing data in %s?" % w.path) self.save_check.vbox.pack_start(label) label.show() self.save_check.connect("response", self.conditional_save_handler) self.save_check.run() # After conditional_save handler fires if not self.save_confirm: return self.log("Writing track data to %s" % w.path) try: fp = open(w.path, "w") except IOError: raise IOException("Cannot write file.", w.path) self.journey.write(fp) def conditional_save_handler(self, widget, id): self.save_confirm = (id == gtk.RESPONSE_ACCEPT) self.save_check.destroy() def help_handler(self, w): "Display help." w = gtk.MessageDialog(type=gtk.MESSAGE_INFO, flags=gtk.DIALOG_DESTROY_WITH_PARENT, buttons=gtk.BUTTONS_OK) w.set_markup(gui_help) w.run() w.destroy() def animate_handler(self, w): "Animate dot placing as though on a storyboard." self.refresh_map() self.expose_event(self.drawing_area) self.redraw(self.drawing_area, 0.5) def log(self, msg): "Notify user of error and die." if self.verbose: print >>sys.stderr, "trackplacer:", msg def fatal_error(self, msg): "Notify user of error and die." w = gtk.MessageDialog(type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK) w.set_markup(msg) w.run() sys.exit(1) if __name__ == "__main__": (options, arguments) = getopt.getopt(sys.argv[1:], "d:hv?", ['directory=', 'help', 'verbose']) verbose = False top = None for (opt, val) in options: if opt in ('-d', '--directory'): top = val elif opt in ('-?', '-h', '--help'): print __doc__ sys.exit(0) elif opt in ('-v', '--verbose'): verbose=True here = os.getcwd() if top: os.chdir(top) else: wesnoth.wmltools.pop_to_top("trackplacer") if arguments: try: TrackEditor(path=os.path.join(here, arguments[0]), verbose=verbose) except IOException, e: if e.lineno: sys.stderr.write(('"%s", line %d: ' % (e.path, e.lineno)) + e.message + "\n") else: sys.stderr.write(e.path + ": " + e.message + "\n") else: while True: try: selector = ModalFileSelector(default=default_map, legend="Track or map file to read") if not selector.path: break TrackEditor(selector.path, verbose=verbose) except IOException, e: w = gtk.MessageDialog(type=gtk.MESSAGE_ERROR, flags=gtk.DIALOG_DESTROY_WITH_PARENT, buttons=gtk.BUTTONS_OK) if e.lineno: errloc = '"%s", line %d:' % (e.path, e.lineno) # Emacs friendliness sys.stderr.write(errloc + " " + e.message + "\n") else: errloc = e.path + ":" w.set_markup(errloc + "\n\n" + e.message) w.run() w.destroy()