#!/usr/bin/python3

import sys

from gi.repository import Gtk, GtkSource


n_windows = 0


def destroy_cb(*args):
    global n_windows
    n_windows -= 1
    if n_windows == 0:
        Gtk.main_quit()


def click_cb(button, buf):
    add_window(buf)


def add_window(buf):
    global n_windows
    view = GtkSource.View.new_with_buffer(buf)
    win = Gtk.Window.new(Gtk.WindowType.TOPLEVEL)
    box = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0)
    btn = Gtk.Button.new_with_label("New window")
    btn.connect("clicked", click_cb, buf)
    box.pack_start(btn, False, True, 0)
    box.pack_start(view, True, True, 0)
    win.add(box)
    win.connect("destroy", destroy_cb)
    win.show_all()
    n_windows += 1


def init(filename):
    buf = GtkSource.Buffer.new(None)
    fp = open(filename, 'r')
    buf.set_text(fp.read())
    fp.close()
    add_window(buf)


init(sys.argv[1])
Gtk.main()
