def calculate_clicked(self, *args):
     from ubiquity.frontend.gtk_components.keyboard_query import (
         KeyboardQuery, )
     self.query = KeyboardQuery(self.controller._wizard)
     self.query.connect('layout_result', self.calculate_result)
     self.query.connect('delete-event', self.calculate_closed)
     # self.controller._wizard.overlay.set_property('greyed', True)
     self.query.set_transient_for(self.page.get_toplevel())
     self.query.run()
 def calculate_clicked(self, *args):
     from ubiquity.frontend.gtk_components.keyboard_query import (
         KeyboardQuery,
     )
     self.query = KeyboardQuery(self.controller._wizard)
     self.query.connect('layout_result', self.calculate_result)
     self.query.connect('delete-event', self.calculate_closed)
     #self.controller._wizard.overlay.set_property('greyed', True)
     self.query.set_transient_for(self.page.get_toplevel())
     self.query.run()
class PageGtk(plugin.PluginUI):
    plugin_title = 'ubiquity/text/keyboard_heading_label'

    def __init__(self, controller, *args, **kwargs):
        self.controller = controller
        self.current_layout = None
        self.keyboard_layout_timeout_id = 0
        self.keyboard_variant_timeout_id = 0
        try:
            from gi.repository import Gtk
            builder = Gtk.Builder()
            self.controller.add_builder(builder)
            builder.add_from_file(os.path.join(
                os.environ['UBIQUITY_GLADE'], 'stepKeyboardConf.ui'))
            builder.connect_signals(self)
            self.page = builder.get_object('stepKeyboardConf')
            self.keyboardlayoutview = builder.get_object('keyboardlayoutview')
            self.keyboardvariantview = builder.get_object(
                'keyboardvariantview')
            self.calculate_keymap_button = builder.get_object('deduce_layout')
            self.keyboard_test = builder.get_object('keyboard_test')
            self.calculate_keymap_button.connect(
                'clicked', self.calculate_clicked)
        except Exception as e:
            self.debug('Could not create keyboard page: %s', e)
            self.page = None
        self.plugin_widgets = self.page

    def plugin_translate(self, lang):
        # TODO Move back into the frontend as we can check
        # isinstance(LabelledEntry) and just call set_label.  We'll need to
        # properly name the debconf keys though (s/inactive_label//)
        test_label = self.controller.get_string('keyboard_test_label', lang)
        self.keyboard_test.set_placeholder_text(test_label)

    def cancel_timeouts(self):
        from gi.repository import GLib
        if self.keyboard_layout_timeout_id:
            GLib.source_remove(self.keyboard_layout_timeout_id)
        if self.keyboard_variant_timeout_id:
            GLib.source_remove(self.keyboard_variant_timeout_id)

    @plugin.only_this_page
    def calculate_result(self, w, keymap):
        l = self.controller.dbfilter.get_locale()
        keymap = keymap.split(':')
        if len(keymap) == 1:
            keymap.append('')
        layout = keyboard_names.layout_human(l, keymap[0])
        variant = keyboard_names.variant_human(l, keymap[0], keymap[1])
        self.set_keyboard(layout)
        self.controller.dbfilter.change_layout(layout)
        self.controller.dbfilter.apply_keyboard(layout, variant)

        # Necessary to clean up references so self.query is garbage collected.
        self.calculate_closed()

    def calculate_closed(self, *args):
        if self.query:
            self.query.destroy()
        self.query = None

    def calculate_clicked(self, *args):
        from ubiquity.frontend.gtk_components.keyboard_query import (
            KeyboardQuery,
        )
        self.query = KeyboardQuery(self.controller._wizard)
        self.query.connect('layout_result', self.calculate_result)
        self.query.connect('delete-event', self.calculate_closed)
        #self.controller._wizard.overlay.set_property('greyed', True)
        self.query.set_transient_for(self.page.get_toplevel())
        self.query.run()

    def on_keyboardlayoutview_row_activated(self, *args):
        self.controller.go_forward()

    @plugin.only_this_page
    def on_keyboard_layout_selected(self, *args):
        if not self.is_automatic:
            # Let's not call this every time the user presses a key.
            from gi.repository import GLib
            if self.keyboard_layout_timeout_id:
                GLib.source_remove(self.keyboard_layout_timeout_id)
            self.keyboard_layout_timeout_id = GLib.timeout_add(
                600, self.keyboard_layout_timeout)
        else:
            self.keyboard_layout_timeout()

    def keyboard_layout_timeout(self, *args):
        layout = self.get_keyboard()
        if layout is not None and layout != self.current_layout:
            self.current_layout = layout
            self.controller.dbfilter.change_layout(layout)
        return False

    def on_keyboardvariantview_row_activated(self, *args):
        self.controller.go_forward()

    @plugin.only_this_page
    def on_keyboard_variant_selected(self, *args):
        if not self.is_automatic:
            # Let's not call this every time the user presses a key.
            from gi.repository import GLib
            if self.keyboard_variant_timeout_id:
                GLib.source_remove(self.keyboard_variant_timeout_id)
            self.keyboard_variant_timeout_id = GLib.timeout_add(
                600, self.keyboard_variant_timeout)
        else:
            self.keyboard_variant_timeout()

    def keyboard_variant_timeout(self, *args):
        layout = self.get_keyboard()
        variant = self.get_keyboard_variant()
        if layout is not None and variant is not None:
            self.controller.dbfilter.apply_keyboard(layout, variant)
        return False

    def set_keyboard_choices(self, choices):
        # Sort the choices including these with accents
        import locale
        try:
            # Try with the current locale (will fail if not generated
            # pre-install)
            locale.setlocale(locale.LC_ALL, '')
        except locale.Error:
            try:
                if os.path.exists("/etc/locale.gen"):
                    # Try with the locale generated by casper
                    with open("/etc/locale.gen", "r") as locale_gen:
                        locale.setlocale(
                            locale.LC_ALL, locale_gen.read().split()[0])
                else:
                    # Try a default, usually working locale
                    locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
                choices.sort(key=lambda c: locale.strxfrm(c.encode('utf-8')))
            except:
                # Let's avoid crashing when we get a bad locale
                choices.sort()

        from gi.repository import Gtk, GObject
        layouts = Gtk.ListStore(GObject.TYPE_STRING)
        self.keyboardlayoutview.set_model(layouts)
        for v in choices:
            layouts.append([v])

        if len(self.keyboardlayoutview.get_columns()) < 1:
            column = Gtk.TreeViewColumn(
                "Layout", Gtk.CellRendererText(), text=0)
            column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
            self.keyboardlayoutview.append_column(column)
            selection = self.keyboardlayoutview.get_selection()
            selection.connect('changed',
                              self.on_keyboard_layout_selected)

        if self.current_layout is not None:
            self.set_keyboard(self.current_layout)

    def set_keyboard(self, layout):
        self.current_layout = layout
        model = self.keyboardlayoutview.get_model()
        if model is None:
            return
        iterator = model.iter_children(None)
        while iterator is not None:
            if misc.utf8(model.get_value(iterator, 0)) == layout:
                path = model.get_path(iterator)
                selection = self.keyboardlayoutview.get_selection()
                if not selection.path_is_selected(path):
                    selection.select_path(path)
                    self.keyboardlayoutview.scroll_to_cell(
                        path, use_align=True, row_align=0.5)
                break
            iterator = model.iter_next(iterator)

    def get_keyboard(self):
        selection = self.keyboardlayoutview.get_selection()
        (model, iterator) = selection.get_selected()
        if iterator is None:
            return None
        else:
            return misc.utf8(model.get_value(iterator, 0))

    def set_keyboard_variant_choices(self, choices):
        from gi.repository import Gtk, GObject
        variants = Gtk.ListStore(GObject.TYPE_STRING)
        self.keyboardvariantview.set_model(variants)
        for v in sorted(choices):
            variants.append([v])

        if len(self.keyboardvariantview.get_columns()) < 1:
            column = Gtk.TreeViewColumn(
                "Variant", Gtk.CellRendererText(), text=0)
            column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
            self.keyboardvariantview.append_column(column)
            selection = self.keyboardvariantview.get_selection()
            selection.connect('changed',
                              self.on_keyboard_variant_selected)

    def set_keyboard_variant(self, variant):
        model = self.keyboardvariantview.get_model()
        if model is None:
            return
        iterator = model.iter_children(None)
        while iterator is not None:
            if misc.utf8(model.get_value(iterator, 0)) == variant:
                path = model.get_path(iterator)
                self.keyboardvariantview.get_selection().select_path(path)
                self.keyboardvariantview.scroll_to_cell(
                    path, use_align=True, row_align=0.5)
                break
            iterator = model.iter_next(iterator)

    def get_keyboard_variant(self):
        selection = self.keyboardvariantview.get_selection()
        (model, iterator) = selection.get_selected()
        if iterator is None:
            return None
        else:
            return misc.utf8(model.get_value(iterator, 0))
class PageGtk(plugin.PluginUI):
    plugin_title = 'ubiquity/text/keyboard_heading_label'

    def __init__(self, controller, *args, **kwargs):
        self.controller = controller
        self.current_layout = None
        self.keyboard_layout_timeout_id = 0
        self.keyboard_variant_timeout_id = 0
        try:
            from gi.repository import Gtk
            builder = Gtk.Builder()
            self.controller.add_builder(builder)
            builder.add_from_file(
                os.path.join(os.environ['UBIQUITY_GLADE'],
                             'stepKeyboardConf.ui'))
            builder.connect_signals(self)
            self.page = builder.get_object('stepKeyboardConf')
            self.keyboardlayoutview = builder.get_object('keyboardlayoutview')
            self.keyboardvariantview = builder.get_object(
                'keyboardvariantview')
            self.calculate_keymap_button = builder.get_object('deduce_layout')
            self.keyboard_test = builder.get_object('keyboard_test')
            self.calculate_keymap_button.connect('clicked',
                                                 self.calculate_clicked)
        except Exception as e:
            self.debug('Could not create keyboard page: %s', e)
            self.page = None
        self.plugin_widgets = self.page

    def plugin_translate(self, lang):
        # TODO Move back into the frontend as we can check
        # isinstance(LabelledEntry) and just call set_label.  We'll need to
        # properly name the debconf keys though (s/inactive_label//)
        test_label = self.controller.get_string('keyboard_test_label', lang)
        self.keyboard_test.set_placeholder_text(test_label)

    def cancel_timeouts(self):
        from gi.repository import GLib
        if self.keyboard_layout_timeout_id:
            GLib.source_remove(self.keyboard_layout_timeout_id)
        if self.keyboard_variant_timeout_id:
            GLib.source_remove(self.keyboard_variant_timeout_id)

    @plugin.only_this_page
    def calculate_result(self, w, keymap):
        ret = self.controller.dbfilter.get_locale()
        keymap = keymap.split(':')
        if len(keymap) == 1:
            keymap.append('')
        layout = keyboard_names.layout_human(ret, keymap[0])
        variant = keyboard_names.variant_human(ret, keymap[0], keymap[1])
        self.set_keyboard(layout)
        self.controller.dbfilter.change_layout(layout)
        self.controller.dbfilter.apply_keyboard(layout, variant)

        # Necessary to clean up references so self.query is garbage collected.
        self.calculate_closed()

    def calculate_closed(self, *args):
        if self.query:
            self.query.destroy()
        self.query = None

    def calculate_clicked(self, *args):
        from ubiquity.frontend.gtk_components.keyboard_query import (
            KeyboardQuery, )
        self.query = KeyboardQuery(self.controller._wizard)
        self.query.connect('layout_result', self.calculate_result)
        self.query.connect('delete-event', self.calculate_closed)
        # self.controller._wizard.overlay.set_property('greyed', True)
        self.query.set_transient_for(self.page.get_toplevel())
        self.query.run()

    def on_keyboardlayoutview_row_activated(self, *args):
        self.controller.go_forward()

    @plugin.only_this_page
    def on_keyboard_layout_selected(self, *args):
        if not self.is_automatic:
            # Let's not call this every time the user presses a key.
            from gi.repository import GLib
            if self.keyboard_layout_timeout_id:
                GLib.source_remove(self.keyboard_layout_timeout_id)
            self.keyboard_layout_timeout_id = GLib.timeout_add(
                600, self.keyboard_layout_timeout)
        else:
            self.keyboard_layout_timeout()

    def keyboard_layout_timeout(self, *args):
        layout = self.get_keyboard()
        if layout is not None and layout != self.current_layout:
            self.current_layout = layout
            self.controller.dbfilter.change_layout(layout)
        return False

    def on_keyboardvariantview_row_activated(self, *args):
        self.controller.go_forward()

    @plugin.only_this_page
    def on_keyboard_variant_selected(self, *args):
        if not self.is_automatic:
            # Let's not call this every time the user presses a key.
            from gi.repository import GLib
            if self.keyboard_variant_timeout_id:
                GLib.source_remove(self.keyboard_variant_timeout_id)
            self.keyboard_variant_timeout_id = GLib.timeout_add(
                600, self.keyboard_variant_timeout)
        else:
            self.keyboard_variant_timeout()

    def keyboard_variant_timeout(self, *args):
        layout = self.get_keyboard()
        variant = self.get_keyboard_variant()
        if layout is not None and variant is not None:
            self.controller.dbfilter.apply_keyboard(layout, variant)
        return False

    def set_keyboard_choices(self, choices):
        # Sort the choices including these with accents
        import locale
        try:
            # Try with the current locale (will fail if not generated
            # pre-install)
            locale.setlocale(locale.LC_ALL, '')
        except locale.Error:
            try:
                if os.path.exists("/etc/locale.gen"):
                    # Try with the locale generated by casper
                    with open("/etc/locale.gen", "r") as locale_gen:
                        locale.setlocale(locale.LC_ALL,
                                         locale_gen.read().split()[0])
                else:
                    # Try a default, usually working locale
                    locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
                choices.sort(key=lambda c: locale.strxfrm(c.encode('utf-8')))
            except Exception:
                # Let's avoid crashing when we get a bad locale
                choices.sort()

        from gi.repository import Gtk, GObject
        layouts = Gtk.ListStore(GObject.TYPE_STRING)
        self.keyboardlayoutview.set_model(layouts)
        for v in choices:
            layouts.append([v])

        if len(self.keyboardlayoutview.get_columns()) < 1:
            column = Gtk.TreeViewColumn("Layout",
                                        Gtk.CellRendererText(),
                                        text=0)
            column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
            self.keyboardlayoutview.append_column(column)
            selection = self.keyboardlayoutview.get_selection()
            selection.connect('changed', self.on_keyboard_layout_selected)

        if self.current_layout is not None:
            self.set_keyboard(self.current_layout)

    def set_keyboard(self, layout):
        self.current_layout = layout
        model = self.keyboardlayoutview.get_model()
        if model is None:
            return
        iterator = model.iter_children(None)
        while iterator is not None:
            if misc.utf8(model.get_value(iterator, 0)) == layout:
                path = model.get_path(iterator)
                selection = self.keyboardlayoutview.get_selection()
                if not selection.path_is_selected(path):
                    selection.select_path(path)
                    self.keyboardlayoutview.scroll_to_cell(path,
                                                           use_align=True,
                                                           row_align=0.5)
                break
            iterator = model.iter_next(iterator)

    def get_keyboard(self):
        selection = self.keyboardlayoutview.get_selection()
        (model, iterator) = selection.get_selected()
        if iterator is None:
            return None
        else:
            return misc.utf8(model.get_value(iterator, 0))

    def set_keyboard_variant_choices(self, choices):
        from gi.repository import Gtk, GObject
        variants = Gtk.ListStore(GObject.TYPE_STRING)
        self.keyboardvariantview.set_model(variants)
        for v in sorted(choices):
            variants.append([v])

        if len(self.keyboardvariantview.get_columns()) < 1:
            column = Gtk.TreeViewColumn("Variant",
                                        Gtk.CellRendererText(),
                                        text=0)
            column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
            self.keyboardvariantview.append_column(column)
            selection = self.keyboardvariantview.get_selection()
            selection.connect('changed', self.on_keyboard_variant_selected)

    def set_keyboard_variant(self, variant):
        model = self.keyboardvariantview.get_model()
        if model is None:
            return
        iterator = model.iter_children(None)
        while iterator is not None:
            if misc.utf8(model.get_value(iterator, 0)) == variant:
                path = model.get_path(iterator)
                self.keyboardvariantview.get_selection().select_path(path)
                self.keyboardvariantview.scroll_to_cell(path,
                                                        use_align=True,
                                                        row_align=0.5)
                break
            iterator = model.iter_next(iterator)

    def get_keyboard_variant(self):
        selection = self.keyboardvariantview.get_selection()
        (model, iterator) = selection.get_selected()
        if iterator is None:
            return None
        else:
            return misc.utf8(model.get_value(iterator, 0))