#!/usr/bin/python

import pango
import gobject
import gtk
import time

class ExecutionTime(object):
    """ helper to make very crude performance measure """
    def __init__(self, info=""):
        self.info = info
    def __enter__(self):
        self.now = time.time()
    def __exit__(self, type, value, stack):
        while gtk.events_pending():
            gtk.main_iteration()
        print "%s: %s" % (self.info, time.time() - self.now)

def on_cursor_changed(treeview):
    (model, it) = treeview.get_selection().get_selected()
    prev = treeview.get_data("prev")
    if prev:
        model[prev][0] = "non active"
    model[it][0] = "active\nso active"
    treeview.set_data("prev", it)

def on_dialog_response(dialog, response, treeview, store):
    dialog.destroy()
    # empty again
    treeview.set_model(None)
    while gtk.events_pending():
        gtk.main_iteration()

    # fixed height mode
    with ExecutionTime("events fixed_height"):
        treeview.set_fixed_height_mode(True)
        treeview.set_model(store)


if __name__ == "__main__":
    # setup model
    store = gtk.ListStore(str, bool)
    for i in range(100000):
        store.append(["%.20i" % i, False])

    treeview = gtk.TreeView()
    cr = gtk.CellRendererText()
    column = gtk.TreeViewColumn("foo", cr, text=0)
    column.set_fixed_width(200)
    column.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
    treeview.append_column(column)
    treeview.connect("cursor-changed", on_cursor_changed)
    treeview.show()

    scroll = gtk.ScrolledWindow()
    scroll.add(treeview)
    scroll.show()
    win = gtk.Window()
    win.add(scroll)
    win.set_default_size(300,300)
    win.show()

    # flush before doing set_model()
    while gtk.events_pending():
        gtk.main_iteration()

    # normal mode
    with ExecutionTime("normal mode"):
        treeview.set_fixed_height_mode(False)
        treeview.set_model(store)

    d = gtk.MessageDialog(win, 
                          buttons=gtk.BUTTONS_OK,
                          message_format="show me the fixed_height one")
    d.connect("response", on_dialog_response, treeview, store)
    d.show()

    gtk.main()

