#!/usr/bin/python

from gi.repository import Gdk, Gtk, Pango


def pango_to_pixels(pu, cells = 1):
    return int((pu * cells + Pango.SCALE / 2) / Pango.SCALE)


def init_size(view, win):
    fd = Pango.FontDescription("Monospace 10")
    view.modify_font(fd)
    fc = view.get_pango_context()
    metrics = fc.get_metrics(fd, fc.get_language())
    cw = pango_to_pixels(metrics.get_approximate_char_width())
    ch = pango_to_pixels(metrics.get_ascent() + metrics.get_descent())
    geom = Gdk.Geometry()
    geom.min_width = cw * 20
    geom.min_height = ch * 10
    geom.base_width = 0
    geom.base_height = 0
    geom.width_inc = cw
    geom.height_inc = ch
    win.set_geometry_hints(view, geom, 
                    Gdk.WindowHints.MIN_SIZE | Gdk.WindowHints.BASE_SIZE |
                    Gdk.WindowHints.RESIZE_INC)
    win.set_default_geometry(80, 32)


def destroy_cb(win):
    Gtk.main_quit()


def init_window():
    view = Gtk.TextView()
    win = Gtk.Window()
    scroll = Gtk.ScrolledWindow()
    scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.ALWAYS)
    scroll.add(view)
    win.add(scroll)
    win.connect("destroy", destroy_cb)
    init_size(view, win)
    win.show_all()


init_window()
Gtk.main()
