
# graph.py
# write a decision tree to a file, graphviz .dot format

# Copyright (c) 2005 by Matthias Urlichs <smurf@smurf.noris.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of Version 2 of the GNU General Public License as
# published by the Free Software Foundation. See the file COPYING.txt
# or (on Debian systems) /usr/share/common-licenses/GPL-2 for details.

"""\
This module prints a decision tree, by writing all the steps to a file.
"""

from keymapper.tree import Reporter
import sys
import unicodedata

def uname(sym):
	try:
		return unicodedata.name(unicode(sym)).lower()
	except ValueError:
		return "U+%4x" % ord(sym)

def symnums(syms):
	return ".".join([str(ord(s)) for s in syms])

class GraphReporter(Reporter):
	"""Report the result as a graphviz .dot file"""
	def __init__(self,file=sys.stdout):
		self.file = file

	def init(self):
		print >>self.file, "digraph keyboard_tree {"

	def exit(self):
		print >>self.file, "}"

	def step(self,stepnr):
		"""Start a new step"""
		self.nr = stepnr

	def keymap(self,map):
		"""This steps selects a unique keymap"""
		print >>self.file, '"Step %d" [label="Map: %s"]' % (self.nr,map.name)
		

	def symbols(self,symbols):
		"""Start a choice: display these symbols"""
		self.syms = symbols

	def choice(self,code,nextstep):
		"""Choice: This keycode leads to that step"""
		syms=[]
		for s,c in self.syms.items():
			if code in c:
				syms.append(s)

		print >>self.file, '"Step %d" -> "S_%d_%s_%d"' % (self.nr,self.nr, symnums(syms), code)
		print >>self.file, '"S_%d_%s_%d" -> "Step %d"' % (self.nr,symnums(syms), code, nextstep.step)
		print >>self.file, '"S_%d_%s_%d" [ label="%s -> %d" ]' % (self.nr, symnums(syms), code, "\\n".join([uname(s) for s in syms]), code)


	def ask(self,sym,no,yes):
		"""Ask whether that symbol is visible"""
		print >>self.file, '"Step %d" [ label="Step %d\\nCheck for %s" ]' % (self.nr,self.nr,uname(sym))
		print >>self.file, '"Step %d" -> "AY-%d" -> "Step %d"' % (self.nr,self.nr,yes.step)
		print >>self.file, '"AY-%d" [ label="Yes" ]' % (self.nr,)
		print >>self.file, '"Step %d" -> "AN-%d" -> "Step %d"' % (self.nr,self.nr,no.step)
		print >>self.file, '"AN-%d" [ label="No" ]' % (self.nr,)

	def finish(self):
		"""Conclude this step"""
		pass

