#!/usr/bin/env python3
import gi
gi.require_version('Gdk', '3.0')
gi.require_version('Gtk', '3.0')
from gi.repository import GObject, Gio, Gdk, Gtk
from sys import argv

def make_button(text, popover):
    return Gtk.MenuButton(child=Gtk.Label(label=text,
                                          use_underline=True),
                          popover=popover)

def make_box():
    return Gtk.Box(margin=12,
                   orientation=Gtk.Orientation.VERTICAL,
                   spacing=6)

def unmap_cb(popover):
    popover.props.relative_to = None

def make_list_popover(iterable, set_cb):
    def make_toggled_cb(text):
        def toggled_cb(button):
            if button.props.active:
                set_cb(text)
        return toggled_cb

    box = make_box();
    last_button=None
    for text in iterable:
        button = Gtk.RadioButton.new_with_label_from_widget(last_button, text)
        button.connect('toggled', make_toggled_cb(text))
        box.add(button)
        last_button = button
    box.show_all()
    return Gtk.Popover(child=box)

def make_popover(label):
    def set_cb(text):
        label.props.label = text

    box = make_box()
    box.add(make_button('_Prunus',
                        make_list_popover(['Apricot','Cherry','Damson',
                                           'Nectarine', 'Peach', 'Plum'],
                                          set_cb)))
    box.add(make_button('_Rubus',
                        make_list_popover(['Blackberry', 'Loganberry',
                                           'Raspberry', 'Tayberry'],
                                          set_cb)))
    popover = Gtk.Popover(child=box, relative_to=label)
    popover.connect('unmap', unmap_cb)
    popover.show_all()

def row_activated_cb(box, row):
    make_popover(row.get_child())

class App(Gtk.Application):
    def __init__(self):
        Gtk.Application.__init__(self, flags=Gio.ApplicationFlags.NON_UNIQUE)

    def do_startup(self):
        def key_press_cb(widget, event):
            try:
                i = int(event.string)
            except:
                return False
            if i & 1:
                box.get_row_at_index(i).grab_focus()
            else:
                box.get_row_at_index(i).activate()
            return True

        Gtk.Application.do_startup(self)
        self.win = Gtk.ApplicationWindow(title='Popover Focus Test')
        self.win.connect('key-press-event', key_press_cb)
        self.win.set_titlebar(Gtk.HeaderBar(show_close_button=True,
                                            title=self.win.props.title))
        box = Gtk.ListBox(margin=12)
        for i in range(10):
            box.add(Gtk.Label(label='Click me'))
        box.connect('row-activated', row_activated_cb)
        self.win.add(box)
        app.add_window(self.win)
        self.win.show_all()

    def do_activate(self):
        Gtk.Application.do_activate(self)
        self.win.present()

GObject.type_register(App)

app=App()
app.run(argv)
