#!/usr/bin/python

import pyatspi
from gi.repository import Gtk

class LevelBarTest(Gtk.Application):
    def __init__(self):
        Gtk.Application.__init__(self)
        self.eventCount = 0
        self.connect("activate", self.onActivate)
        
    def onActivate(self, data=None):
        window = Gtk.Window(type=Gtk.WindowType.TOPLEVEL)
        grid = Gtk.Grid()
        window.add(grid)

        scrolledWindow = Gtk.ScrolledWindow()
        scrolledWindow.set_size_request(400, 300)
        grid.attach(scrolledWindow, 0, 0, 1, 1)

        self.textView = Gtk.TextView()
        self.textView.set_editable(False)
        scrolledWindow.add(self.textView)

        levelBarGrid = Gtk.Grid()
        grid.attach(levelBarGrid, 0, 1, 1, 1)

        self.levelBar = Gtk.LevelBar.new_for_interval(0, 4)
        self.levelBar.set_size_request(400, -1)
        levelBarGrid.attach(self.levelBar, 0, 0, 1, 1)

        self.notebook = Gtk.Notebook()
        for string in ("sucks", "meh", "good enough", "great", "awesome"):
            self.notebook.append_page(Gtk.Label(string), None)
        self.notebook.set_show_tabs(False)
        levelBarGrid.attach(self.notebook, 0, 1, 1, 1)

        btn = Gtk.Button("+")
        btn.set_size_request(0, 0)
        btn.connect("clicked", self.changeLevel, 1)
        levelBarGrid.attach(btn, 1, 0, 1, 1)

        btn.grab_focus()
        window.show_all()
        self.add_window(window)

        pyatspi.Registry.registerEventListener(
            self.onFocus,
            "object:state-changed:focused",
            "focus:")

    def changeLevel(self, widget, increment):
        value = self.levelBar.get_value() + increment
        if value == 5:
            value = 0

        self.notebook.set_current_page(value)
        self.levelBar.set_value(value)

    def onFocus(self, event):
        self.eventCount += 1
        textBuffer = self.textView.get_buffer()
        string = "\n%i\t%s\n\tIs focused: %s" % \
            (self.eventCount, event, event.source.getState().contains(pyatspi.STATE_FOCUSED))
        textBuffer.insert(textBuffer.get_end_iter(), string)
        self.textView.scroll_to_mark(textBuffer.get_insert(), 0.0, True, 1.0, 1.0)

if __name__ == "__main__":
    app = LevelBarTest()
    app.run(None)
