# Uses algorithms Wrap and SMAWK from http://www.ics.uci.edu/~eppstein/PADS/
# to properly wordwrap text in PyGUI on the canvas.  The algorithm is pretty
# simple but works really well and consistently no matter what you hand it.
# Some fonts don't report their size right so they may bleed to the right a bit.
# You'll have to install PyGUI http://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/
# to play with this.

from GUI import Application, ScrollableView, Document, Window, FileType, Cursor, rgb, Font
from GUI.Geometry import pt_in_rect, offset_rect, rects_intersect
from GUI.StdColors import black, red
from Wrap import wrap

class MokoApp(Application):

    def __init__(self):
        Application.__init__(self)
        self.file_type = FileType(name = "Moko Utu Client", suffix="txt")
    
    def open_app(self):
        self.new_cmd()

    def make_document(self, fileref):
        return MokoDoc()

    def make_window(self, document):
        win = Window(size = (400,400), document = document)
        view = MokoView(model = document, extent = (0,0,1000,100), scrolling = 'hv')
        win.place(view, left = 0, top = 0, right = 0, bottom = 0, sticky = 'nsew')
        win.show()

class MokoDoc(Document):
    data = None

    def new_contents(self):
        self.data = """
        Use File->Open to see something with .txt extensions.
        Use click to increase and shift-click to decrease font size.
        Resize the window and it'll track it.  All using the 
        algorithms Wrap and SMAWK from http://www.ics.uci.edu/~eppstein/PADS/
        to do the work.
        """

    def read_contents(self, file):
        self.data = file.read()

    def write_contents(self, file):
        file.write(self.data)
        file.close()

class MokoView(ScrollableView):
    font = Font("Inconsolata", 20, "bold")

    def draw(self, canvas, update_rect):
        """Word wraps the loaded document using the online
        minima method so that the text fits in the viewed_rect.
        """
        l,t,r,b = self.viewed_rect()
        wrapped = wrap(self.model.data, target=r-20, measure=self.font.width)
        canvas.font = self.font
        for i, line in enumerate(wrapped): 
            self.draw_line(canvas, i, line)
        canvas.stroke()

    def mouse_down(self, event):
        change = -1 if event.shift else 1
        self.font = Font("Inconsolata", self.font.size + change, "bold")
        print "new size: %d" % self.font.size
        self.invalidate()

    def draw_line(self, canvas, i, line):
        start = i * self.font.line_height
        canvas.moveto(5, start+self.font.height)
        canvas.show_text(line)

MokoApp().run()