Exemple #1
0
 def on_change_mode(self, mode):
     self.listenkbd.stop()
     self.listenkbd = ListenKbd(self.label,
                                logger=self.logger,
                                mode=mode,
                                nosudo=self.nosudo)
     self.listenkbd.start()
Exemple #2
0
 def on_show_keys(self, widget, data=None):
     if widget.get_active():
         self.logger.debug("Screenkey enabled.")
         self.listenkbd = ListenKbd(self.label,
                                    logger=self.logger,
                                    mode=self.options['mode'])
         self.listenkbd.start()
     else:
         self.logger.debug("Screenkey disabled.")
         self.listenkbd.stop()
Exemple #3
0
 def on_show_keys(self, widget, data=None):
     if widget.get_active():
         self.logger.debug("Screenkey enabled.")
         self.listenkbd = ListenKbd(self.label, logger=self.logger, mode=self.options["mode"], nosudo=self.nosudo)
         self.listenkbd.start()
     else:
         self.logger.debug("Screenkey disabled.")
         self.listenkbd.stop()
Exemple #4
0
 def on_show_keys(self, widget, data=None):
     if widget.get_active():
         self._disabled = False
         self.logger.debug("Screenkey enabled.")
         self.listenkbd = ListenKbd(self.label, logger=self.logger,
                                    mode=self.options['mode'])
         self.listenkbd.start()
     else:
         self.logger.debug("Screenkey disabled.")
         self._disabled = True
         self.listenkbd.stop()
Exemple #5
0
    def __init__(self, logger, nodetach):
        gtk.Window.__init__(self)

        self.timer = None
        self.logger = logger

        self.options = self.load_state()
        if not self.options:
            self.options = {
                "timeout": 2.5,
                "position": POS_BOTTOM,
                "size": SIZE_MEDIUM,
                "mode": MODE_NORMAL,
                "hotkey": "<Ctrl>F1",
            }

        if not nodetach:
            self.logger.debug("Detach from the parent.")
            self.drop_tty()

        self.set_skip_taskbar_hint(True)
        self.set_skip_pager_hint(True)
        self.set_keep_above(True)
        self.set_decorated(False)
        self.stick()
        self.set_property("accept-focus", False)
        self.set_property("focus-on-map", False)
        self.set_position(gtk.WIN_POS_CENTER)
        bgcolor = gtk.gdk.color_parse("black")
        self.modify_bg(gtk.STATE_NORMAL, bgcolor)
        self.set_opacity(0.7)

        gobject.signal_new("text-changed", gtk.Label, gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ())
        self.label = gtk.Label()
        self.label.set_justify(gtk.JUSTIFY_RIGHT)
        self.label.set_ellipsize(pango.ELLIPSIZE_START)
        self.label.connect("text-changed", self.on_label_change)
        self.label.show()
        self.add(self.label)

        self.screen_width = gtk.gdk.screen_width()
        self.screen_height = gtk.gdk.screen_height()
        self.set_window_size(self.options["size"])

        self.set_gravity(gtk.gdk.GRAVITY_CENTER)
        self.set_xy_position(self.options["position"])

        self.listenkbd = ListenKbd(self.label, logger=self.logger, mode=self.options["mode"])
        self.listenkbd.start()

        menu = gtk.Menu()

        show_item = gtk.CheckMenuItem(_("Show keys"))
        show_item.set_active(True)
        show_item.connect("toggled", self.on_show_keys)
        show_item.show()
        menu.append(show_item)

        preferences_item = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
        preferences_item.connect("activate", self.on_preferences_dialog)
        preferences_item.show()
        menu.append(preferences_item)

        about_item = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
        about_item.connect("activate", self.on_about_dialog)
        about_item.show()
        menu.append(about_item)

        separator_item = gtk.SeparatorMenuItem()
        separator_item.show()
        menu.append(separator_item)

        image = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        image.connect("activate", self.quit)
        image.show()
        menu.append(image)
        menu.show()

        try:
            import appindicator

            self.systray = appindicator.Indicator(
                APP_NAME, "indicator-messages", appindicator.CATEGORY_APPLICATION_STATUS
            )
            self.systray.set_status(appindicator.STATUS_ACTIVE)
            self.systray.set_attention_icon("indicator-messages-new")
            self.systray.set_icon("preferences-desktop-keyboard-shortcuts")
            self.systray.set_menu(menu)
            self.logger.debug("Using AppIndicator.")
        except (ImportError):
            self.systray = gtk.StatusIcon()
            self.systray.set_from_icon_name("preferences-desktop-keyboard-shortcuts")
            self.systray.connect("popup-menu", self.on_statusicon_popup, menu)
            self.logger.debug("Using StatusIcon.")

        self.connect("delete-event", self.quit)
        keybinder.bind(self.options["hotkey"], self.hotkey_cb, show_item)
Exemple #6
0
class Screenkey(gtk.Window):

    POSITIONS = {POS_TOP: _("Top"), POS_CENTER: _("Center"), POS_BOTTOM: _("Bottom")}
    SIZES = {SIZE_LARGE: _("Large"), SIZE_MEDIUM: _("Medium"), SIZE_SMALL: _("Small")}
    MODES = {MODE_RAW: _("Raw"), MODE_NORMAL: _("Normal")}

    STATE_FILE = os.path.join(glib.get_user_cache_dir(), "screenkey.dat")

    _disabled = False

    def __init__(self, logger, nodetach):
        gtk.Window.__init__(self)

        self.timer = None
        self.logger = logger

        self.options = self.load_state()
        if not self.options:
            self.options = {
                "timeout": 2.5,
                "position": POS_BOTTOM,
                "size": SIZE_MEDIUM,
                "mode": MODE_NORMAL,
                "hotkey": "<Ctrl>F1",
            }

        if not nodetach:
            self.logger.debug("Detach from the parent.")
            self.drop_tty()

        self.set_skip_taskbar_hint(True)
        self.set_skip_pager_hint(True)
        self.set_keep_above(True)
        self.set_decorated(False)
        self.stick()
        self.set_property("accept-focus", False)
        self.set_property("focus-on-map", False)
        self.set_position(gtk.WIN_POS_CENTER)
        bgcolor = gtk.gdk.color_parse("black")
        self.modify_bg(gtk.STATE_NORMAL, bgcolor)
        self.set_opacity(0.7)

        gobject.signal_new("text-changed", gtk.Label, gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ())
        self.label = gtk.Label()
        self.label.set_justify(gtk.JUSTIFY_RIGHT)
        self.label.set_ellipsize(pango.ELLIPSIZE_START)
        self.label.connect("text-changed", self.on_label_change)
        self.label.show()
        self.add(self.label)

        self.screen_width = gtk.gdk.screen_width()
        self.screen_height = gtk.gdk.screen_height()
        self.set_window_size(self.options["size"])

        self.set_gravity(gtk.gdk.GRAVITY_CENTER)
        self.set_xy_position(self.options["position"])

        self.listenkbd = ListenKbd(self.label, logger=self.logger, mode=self.options["mode"])
        self.listenkbd.start()

        menu = gtk.Menu()

        show_item = gtk.CheckMenuItem(_("Show keys"))
        show_item.set_active(True)
        show_item.connect("toggled", self.on_show_keys)
        show_item.show()
        menu.append(show_item)

        preferences_item = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
        preferences_item.connect("activate", self.on_preferences_dialog)
        preferences_item.show()
        menu.append(preferences_item)

        about_item = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
        about_item.connect("activate", self.on_about_dialog)
        about_item.show()
        menu.append(about_item)

        separator_item = gtk.SeparatorMenuItem()
        separator_item.show()
        menu.append(separator_item)

        image = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        image.connect("activate", self.quit)
        image.show()
        menu.append(image)
        menu.show()

        try:
            import appindicator

            self.systray = appindicator.Indicator(
                APP_NAME, "indicator-messages", appindicator.CATEGORY_APPLICATION_STATUS
            )
            self.systray.set_status(appindicator.STATUS_ACTIVE)
            self.systray.set_attention_icon("indicator-messages-new")
            self.systray.set_icon("preferences-desktop-keyboard-shortcuts")
            self.systray.set_menu(menu)
            self.logger.debug("Using AppIndicator.")
        except (ImportError):
            self.systray = gtk.StatusIcon()
            self.systray.set_from_icon_name("preferences-desktop-keyboard-shortcuts")
            self.systray.connect("popup-menu", self.on_statusicon_popup, menu)
            self.logger.debug("Using StatusIcon.")

        self.connect("delete-event", self.quit)
        keybinder.bind(self.options["hotkey"], self.hotkey_cb, show_item)

    def quit(self, widget, data=None):
        self.listenkbd.stop()
        gtk.main_quit()

    def load_state(self):
        """Load stored options"""
        options = None
        try:
            f = open(self.STATE_FILE, "r")
            try:
                options = pickle.load(f)
                self.logger.debug("Options loaded.")
            except:
                f.close()
        except IOError:
            self.logger.debug("file %s does not exists." % self.STATE_FILE)
        return options

    def store_state(self, options):
        """Store options"""
        try:
            f = open(self.STATE_FILE, "w")
            try:
                pickle.dump(options, f)
                self.logger.debug("Options saved.")
            except:
                f.close()
        except IOError:
            self.logger.debug("Cannot open %s." % self.STATE_FILE)

    def set_window_size(self, setting):
        """Set window and label size."""
        window_width = self.screen_width
        window_height = -1

        if setting == SIZE_LARGE:
            window_height = 24 * self.screen_height / 100
        if setting == SIZE_MEDIUM:
            window_height = 12 * self.screen_height / 100
        if setting == SIZE_SMALL:
            window_height = 8 * self.screen_height / 100

        attr = pango.AttrList()
        attr.change(pango.AttrSize((50 * window_height / 100) * 1000, 0, -1))
        attr.change(pango.AttrFamily("Sans", 0, -1))
        attr.change(pango.AttrWeight(pango.WEIGHT_BOLD, 0, -1))
        attr.change(pango.AttrForeground(65535, 65535, 65535, 0, -1))

        self.label.set_attributes(attr)
        self.resize(window_width, window_height)

    def set_xy_position(self, setting):
        """Set window position."""
        window_width, window_height = self.get_size()
        if setting == POS_TOP:
            self.move(0, window_height * 2)
        if setting == POS_CENTER:
            self.move(0, self.screen_height / 2)
        if setting == POS_BOTTOM:
            self.move(0, self.screen_height - window_height * 2)

    def on_statusicon_popup(self, widget, button, timestamp, data=None):
        if button == 3:
            if data:
                data.show()
                data.popup(None, None, gtk.status_icon_position_menu, 3, timestamp, widget)

    def on_label_change(self, widget, data=None):
        if not self._disabled:
            if not self.get_property("visible"):
                gtk.gdk.threads_enter()
                self.set_xy_position(self.options["position"])
                self.stick()
                self.show()
                gtk.gdk.threads_leave()
            if self.timer:
                self.timer.cancel()
            self.timer = Timer(self.options["timeout"], self.on_timeout)
            self.timer.start()
        else:
            gtk.gdk.threads_enter()
            self.hide()
            self.label.set_text("")
            gtk.gdk.threads_leave()

    def on_timeout(self):
        gtk.gdk.threads_enter()
        self.hide()
        self.label.set_text("")
        gtk.gdk.threads_leave()

    def on_change_mode(self, mode):
        self.listenkbd.stop()
        self.listenkbd = ListenKbd(self.label, logger=self.logger, mode=mode)
        self.listenkbd.start()

    def on_show_keys(self, widget, data=None):
        if widget.get_active():
            self._disabled = False
            self.logger.debug("Screenkey enabled.")
            self.listenkbd = ListenKbd(self.label, logger=self.logger, mode=self.options["mode"])
            self.listenkbd.start()
        else:
            self.logger.debug("Screenkey disabled.")
            self._disabled = True
            self.listenkbd.stop()

    def hotkey_cb(self, widget, data=None):
        if widget.get_active():
            self.logger.debug("Hotkey Pressed: %s." % self.options["hotkey"])
            self._disabled = True
            widget.set_active(False)
        else:
            self._disabled = False
            widget.set_active(True)

    def on_preferences_dialog(self, widget, data=None):
        prefs = gtk.Dialog(
            APP_NAME, None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
        )

        def on_sb_time_changed(widget, data=None):
            self.options["timeout"] = widget.get_value()
            self.logger.debug("Timeout value changed.")

        def on_cbox_sizes_changed(widget, data=None):
            index = widget.get_active()
            if index >= 0:
                self.options["size"] = index
                self.set_window_size(self.options["size"])
                self.logger.debug("Window size changed.")

        def on_cbox_modes_changed(widget, data=None):
            index = widget.get_active()
            if index >= 0:
                self.options["mode"] = index
                self.on_change_mode(self.options["mode"])
                self.logger.debug("Key mode changed.")

        def on_cbox_changed(widget, data=None):
            index = widget.get_active()
            name = widget.get_name()
            if index >= 0:
                self.options[name] = index
                self.logger.debug("Window position changed.")

        def on_entry_hotkey_changed(widget, data=None):
            self.options["hotkey"] = widget.get_text()
            self.logger.debug("Hotkey value Changed")

        frm_main = gtk.Frame(_("Preferences"))
        frm_main.set_border_width(6)
        vbox_main = gtk.VBox()

        frm_time = gtk.Frame(_("<b>Time</b>"))
        frm_time.set_border_width(4)
        frm_time.get_label_widget().set_use_markup(True)
        frm_time.set_shadow_type(gtk.SHADOW_NONE)
        hbox_time = gtk.HBox()
        lbl_time1 = gtk.Label(_("Display for"))
        lbl_time2 = gtk.Label(_("seconds"))
        sb_time = gtk.SpinButton(digits=1)
        sb_time.set_increments(0.5, 1.0)
        sb_time.set_range(0.5, 10.0)
        sb_time.set_numeric(True)
        sb_time.set_update_policy(gtk.UPDATE_IF_VALID)
        sb_time.set_value(self.options["timeout"])
        sb_time.connect("value-changed", on_sb_time_changed)
        hbox_time.pack_start(lbl_time1, expand=False, fill=False, padding=6)
        hbox_time.pack_start(sb_time, expand=False, fill=False, padding=4)
        hbox_time.pack_start(lbl_time2, expand=False, fill=False, padding=4)
        frm_time.add(hbox_time)
        frm_time.show_all()

        frm_aspect = gtk.Frame(_("<b>Aspect</b>"))
        frm_aspect.set_border_width(4)
        frm_aspect.get_label_widget().set_use_markup(True)
        frm_aspect.set_shadow_type(gtk.SHADOW_NONE)
        vbox_aspect = gtk.VBox(spacing=6)

        hbox1_aspect = gtk.HBox()

        lbl_positions = gtk.Label(_("Position"))
        cbox_positions = gtk.combo_box_new_text()
        cbox_positions.set_name("position")
        for key, value in self.POSITIONS.items():
            cbox_positions.insert_text(key, value)
        cbox_positions.set_active(self.options["position"])
        cbox_positions.connect("changed", on_cbox_changed)

        hbox1_aspect.pack_start(lbl_positions, expand=False, fill=False, padding=6)
        hbox1_aspect.pack_start(cbox_positions, expand=False, fill=False, padding=4)

        hbox2_aspect = gtk.HBox()

        lbl_sizes = gtk.Label(_("Size"))
        cbox_sizes = gtk.combo_box_new_text()
        cbox_sizes.set_name("size")
        for key, value in self.SIZES.items():
            cbox_sizes.insert_text(key, value)
        cbox_sizes.set_active(self.options["size"])
        cbox_sizes.connect("changed", on_cbox_sizes_changed)

        hbox2_aspect.pack_start(lbl_sizes, expand=False, fill=False, padding=6)
        hbox2_aspect.pack_start(cbox_sizes, expand=False, fill=False, padding=4)

        vbox_aspect.pack_start(hbox1_aspect)
        vbox_aspect.pack_start(hbox2_aspect)
        frm_aspect.add(vbox_aspect)

        frm_kbd = gtk.Frame(_("<b>Keys</b>"))
        frm_kbd.set_border_width(4)
        frm_kbd.get_label_widget().set_use_markup(True)
        frm_kbd.set_shadow_type(gtk.SHADOW_NONE)
        hbox_kbd = gtk.HBox()
        lbl_kbd = gtk.Label(_("Mode"))
        cbox_modes = gtk.combo_box_new_text()
        cbox_modes.set_name("mode")
        for key, value in self.MODES.items():
            cbox_modes.insert_text(key, value)
        cbox_modes.set_active(self.options["mode"])
        cbox_modes.connect("changed", on_cbox_modes_changed)
        hbox_kbd.pack_start(lbl_kbd, expand=False, fill=False, padding=6)
        hbox_kbd.pack_start(cbox_modes, expand=False, fill=False, padding=4)
        frm_kbd.add(hbox_kbd)

        frm_hotkey = gtk.Frame(_("<b>Hot Keys</b>"))
        frm_hotkey.set_border_width(4)
        frm_hotkey.get_label_widget().set_use_markup(True)
        frm_hotkey.set_shadow_type(gtk.SHADOW_NONE)
        hbox_hotkey = gtk.HBox()
        lbl_hotkey = gtk.Label(_("Shortcut"))
        entry_hotkey = gtk.Entry()
        entry_hotkey.set_text(self.options["hotkey"])
        entry_hotkey.set_width_chars(10)
        entry_hotkey.connect("changed", on_entry_hotkey_changed)
        hbox_hotkey.pack_start(lbl_hotkey, expand=False, fill=False, padding=6)
        hbox_hotkey.pack_start(entry_hotkey, expand=False, fill=False, padding=4)
        frm_hotkey.add(hbox_hotkey)

        vbox_main.pack_start(frm_time, False, False, 6)
        vbox_main.pack_start(frm_aspect, False, False, 6)
        vbox_main.pack_start(frm_kbd, False, False, 6)
        vbox_main.pack_start(frm_hotkey, False, False, 6)
        frm_main.add(vbox_main)

        prefs.vbox.pack_start(frm_main)
        prefs.set_destroy_with_parent(True)
        prefs.set_resizable(False)
        prefs.set_has_separator(False)
        prefs.set_default_response(gtk.RESPONSE_CLOSE)
        prefs.vbox.show_all()
        response = prefs.run()
        if response:
            self.store_state(self.options)
        prefs.destroy()

    def on_about_dialog(self, widget, data=None):
        about = gtk.AboutDialog()
        about.set_program_name(APP_NAME)
        about.set_version(VERSION)
        about.set_copyright(u"2010 \u00a9 %s" % AUTHOR)
        about.set_comments(APP_DESC)
        about.set_documenters([u"Jos\xe9 Mar\xeda Quiroga <*****@*****.**>"])
        about.set_website(APP_URL)
        about.set_icon_name("preferences-desktop-keyboard-shortcuts")
        about.set_logo_icon_name("preferences-desktop-keyboard-shortcuts")
        about.run()
        about.destroy()

    def drop_tty(self):
        # We fork and setsid so that we drop the controlling
        # tty.
        if os.fork() != 0:
            os._exit(0)

        os.setsid()
Exemple #7
0
 def on_change_mode(self, mode):
     self.listenkbd.stop()
     self.listenkbd = ListenKbd(self.label, logger=self.logger, mode=mode)
     self.listenkbd.start()
Exemple #8
0
    def __init__(self, logger, nodetach):
        gtk.Window.__init__(self)

        self.timer = None
        self.logger = logger

        self.options = self.load_state()
        if not self.options:
            self.options = {
                'timeout': 2.5,
                'position': POS_BOTTOM,
                'size': SIZE_MEDIUM,
                'mode': MODE_NORMAL,
                'hotkey': '<Ctrl>F1',
                }

        if not nodetach:
            self.logger.debug("Detach from the parent.")
            self.drop_tty()

        self.set_skip_taskbar_hint(True)
        self.set_skip_pager_hint(True)
        self.set_keep_above(True)
        self.set_decorated(False)
        self.stick()
        self.set_property('accept-focus', False)
        self.set_property('focus-on-map', False)
        self.set_position(gtk.WIN_POS_CENTER)
        bgcolor = gtk.gdk.color_parse("black")
        self.modify_bg(gtk.STATE_NORMAL, bgcolor)
        self.set_opacity(0.7)

        gobject.signal_new("text-changed", gtk.Label, 
                        gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ())
        self.label = gtk.Label()
        self.label.set_justify(gtk.JUSTIFY_RIGHT)
        self.label.set_ellipsize(pango.ELLIPSIZE_START)
        self.label.connect("text-changed", self.on_label_change)
        self.label.show()
        self.add(self.label)

        self.screen_width = gtk.gdk.screen_width()   
        self.screen_height = gtk.gdk.screen_height() 
        self.set_window_size(self.options['size'])

        self.set_gravity(gtk.gdk.GRAVITY_CENTER)
        self.set_xy_position(self.options['position'])

        self.listenkbd = ListenKbd(self.label, logger=self.logger, 
                                   mode=self.options['mode'])
        self.listenkbd.start()

        menu = gtk.Menu()

        show_item = gtk.CheckMenuItem(_("Show keys"))
        show_item.set_active(True)
        show_item.connect("toggled", self.on_show_keys)
        show_item.show()
        menu.append(show_item)

        preferences_item = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
        preferences_item.connect("activate", self.on_preferences_dialog)
        preferences_item.show()
        menu.append(preferences_item)


        about_item = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
        about_item.connect("activate", self.on_about_dialog)
        about_item.show()
        menu.append(about_item)

        separator_item = gtk.SeparatorMenuItem()
        separator_item.show()
        menu.append(separator_item)

        image = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        image.connect("activate", self.quit)
        image.show()
        menu.append(image)
        menu.show()

        try:
            import appindicator
            self.systray = appindicator.Indicator(APP_NAME, 
                           'indicator-messages', 
                            appindicator.CATEGORY_APPLICATION_STATUS)
            self.systray.set_status(appindicator.STATUS_ACTIVE)
            self.systray.set_attention_icon("indicator-messages-new")
            self.systray.set_icon(
                    "preferences-desktop-keyboard-shortcuts")
            self.systray.set_menu(menu)
            self.logger.debug("Using AppIndicator.")
        except(ImportError):
            self.systray = gtk.StatusIcon()
            self.systray.set_from_icon_name(
                    "preferences-desktop-keyboard-shortcuts")
            self.systray.connect("popup-menu", 
                    self.on_statusicon_popup, menu)
            self.logger.debug("Using StatusIcon.")

        self.connect("delete-event", self.quit)
        keybinder.bind(self.options['hotkey'], self.hotkey_cb, show_item)
Exemple #9
0
class Screenkey(gtk.Window):

    POSITIONS = {
        POS_TOP:_('Top'),
        POS_CENTER:_('Center'),
        POS_BOTTOM:_('Bottom'),
    }
    SIZES = {
        SIZE_LARGE:_('Large'),
        SIZE_MEDIUM:_('Medium'),
        SIZE_SMALL:_('Small'),
    }
    MODES = {
        MODE_RAW:_('Raw'),
        MODE_NORMAL:_('Normal'),
    }

    STATE_FILE = os.path.join(glib.get_user_cache_dir(), 
                              'screenkey.dat')

    _disabled = False

    def __init__(self, logger, nodetach):
        gtk.Window.__init__(self)

        self.timer = None
        self.logger = logger

        self.options = self.load_state()
        if not self.options:
            self.options = {
                'timeout': 2.5,
                'position': POS_BOTTOM,
                'size': SIZE_MEDIUM,
                'mode': MODE_NORMAL,
                'hotkey': '<Ctrl>F1',
                }

        if not nodetach:
            self.logger.debug("Detach from the parent.")
            self.drop_tty()

        self.set_skip_taskbar_hint(True)
        self.set_skip_pager_hint(True)
        self.set_keep_above(True)
        self.set_decorated(False)
        self.stick()
        self.set_property('accept-focus', False)
        self.set_property('focus-on-map', False)
        self.set_position(gtk.WIN_POS_CENTER)
        bgcolor = gtk.gdk.color_parse("black")
        self.modify_bg(gtk.STATE_NORMAL, bgcolor)
        self.set_opacity(0.7)

        gobject.signal_new("text-changed", gtk.Label, 
                        gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ())
        self.label = gtk.Label()
        self.label.set_justify(gtk.JUSTIFY_RIGHT)
        self.label.set_ellipsize(pango.ELLIPSIZE_START)
        self.label.connect("text-changed", self.on_label_change)
        self.label.show()
        self.add(self.label)

        self.screen_width = gtk.gdk.screen_width()   
        self.screen_height = gtk.gdk.screen_height() 
        self.set_window_size(self.options['size'])

        self.set_gravity(gtk.gdk.GRAVITY_CENTER)
        self.set_xy_position(self.options['position'])

        self.listenkbd = ListenKbd(self.label, logger=self.logger, 
                                   mode=self.options['mode'])
        self.listenkbd.start()

        menu = gtk.Menu()

        show_item = gtk.CheckMenuItem(_("Show keys"))
        show_item.set_active(True)
        show_item.connect("toggled", self.on_show_keys)
        show_item.show()
        menu.append(show_item)

        preferences_item = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
        preferences_item.connect("activate", self.on_preferences_dialog)
        preferences_item.show()
        menu.append(preferences_item)


        about_item = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
        about_item.connect("activate", self.on_about_dialog)
        about_item.show()
        menu.append(about_item)

        separator_item = gtk.SeparatorMenuItem()
        separator_item.show()
        menu.append(separator_item)

        image = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        image.connect("activate", self.quit)
        image.show()
        menu.append(image)
        menu.show()

        try:
            import appindicator
            self.systray = appindicator.Indicator(APP_NAME, 
                           'indicator-messages', 
                            appindicator.CATEGORY_APPLICATION_STATUS)
            self.systray.set_status(appindicator.STATUS_ACTIVE)
            self.systray.set_attention_icon("indicator-messages-new")
            self.systray.set_icon(
                    "preferences-desktop-keyboard-shortcuts")
            self.systray.set_menu(menu)
            self.logger.debug("Using AppIndicator.")
        except(ImportError):
            self.systray = gtk.StatusIcon()
            self.systray.set_from_icon_name(
                    "preferences-desktop-keyboard-shortcuts")
            self.systray.connect("popup-menu", 
                    self.on_statusicon_popup, menu)
            self.logger.debug("Using StatusIcon.")

        self.connect("delete-event", self.quit)
        keybinder.bind(self.options['hotkey'], self.hotkey_cb, show_item)

    def quit(self, widget, data=None):
        self.listenkbd.stop()
        gtk.main_quit()

    def load_state(self):
        """Load stored options"""
        options = None
        try:
            f = open(self.STATE_FILE, 'r')
            try:
                options = pickle.load(f)
                self.logger.debug("Options loaded.")
            except:
                f.close()
        except IOError:
            self.logger.debug("file %s does not exists." % 
                              self.STATE_FILE)
        return options

    def store_state(self, options):
        """Store options"""
        try:
            f = open(self.STATE_FILE, 'w')
            try:
                pickle.dump(options, f)
                self.logger.debug("Options saved.")
            except:
                f.close()
        except IOError:
            self.logger.debug("Cannot open %s." % self.STATE_FILE)

    def set_window_size(self, setting):
        """Set window and label size."""
        window_width = self.screen_width
        window_height = -1

        if setting == SIZE_LARGE:
            window_height = 24 * self.screen_height / 100
        if setting == SIZE_MEDIUM:
            window_height = 12 * self.screen_height / 100
        if setting == SIZE_SMALL:
            window_height = 8 * self.screen_height / 100

        attr = pango.AttrList()
        attr.change(pango.AttrSize((
                    50 * window_height / 100) * 1000, 0, -1))
        attr.change(pango.AttrFamily("Sans", 0, -1))
        attr.change(pango.AttrWeight(pango.WEIGHT_BOLD, 0, -1))
        attr.change(pango.AttrForeground(65535, 65535, 65535, 0, -1))

        self.label.set_attributes(attr)
        self.resize(window_width, window_height)

    def set_xy_position(self, setting):
        """Set window position."""
        window_width, window_height = self.get_size()
        if setting == POS_TOP:
            self.move(0, window_height * 2)
        if setting == POS_CENTER:
            self.move(0, self.screen_height / 2)
        if setting == POS_BOTTOM:
            self.move(0, self.screen_height - window_height * 2)

    def on_statusicon_popup(self, widget, button, timestamp, data=None):
        if button == 3:
            if data:
                data.show()
                data.popup(None, None, gtk.status_icon_position_menu, 
                           3, timestamp, widget)

    def on_label_change(self, widget, data=None):
        if not self._disabled:
            if not self.get_property('visible'):
                gtk.gdk.threads_enter()
                self.set_xy_position(self.options['position'])
                self.stick()
                self.show()
                gtk.gdk.threads_leave()
            if self.timer:
                self.timer.cancel()
            self.timer = Timer(self.options['timeout'], self.on_timeout)
            self.timer.start()
        else:
            gtk.gdk.threads_enter()
            self.hide()
            self.label.set_text("")
            gtk.gdk.threads_leave()

    def on_timeout(self):
        gtk.gdk.threads_enter()
        self.hide()
        self.label.set_text("")
        gtk.gdk.threads_leave()

    def on_change_mode(self, mode):
        self.listenkbd.stop()
        self.listenkbd = ListenKbd(self.label, logger=self.logger, 
                                   mode=mode)
        self.listenkbd.start()

    def on_show_keys(self, widget, data=None):
        if widget.get_active():
            self._disabled = False
            self.logger.debug("Screenkey enabled.")
            self.listenkbd = ListenKbd(self.label, logger=self.logger, 
                                       mode=self.options['mode'])
            self.listenkbd.start()
        else:
            self.logger.debug("Screenkey disabled.")
            self._disabled = True
            self.listenkbd.stop()
    
    def hotkey_cb(self, widget, data=None):
        if widget.get_active():
            self.logger.debug("Hotkey Pressed: %s." % self.options['hotkey'])
            self._disabled = True
            widget.set_active(False)
        else:
            self._disabled = False
            widget.set_active(True)

    def on_preferences_dialog(self, widget, data=None):
        prefs = gtk.Dialog(APP_NAME, None, 
                    gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, 
                    (gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE))

        def on_sb_time_changed(widget, data=None):
            self.options['timeout'] = widget.get_value()
            self.logger.debug("Timeout value changed.")

        def on_cbox_sizes_changed(widget, data=None):
            index = widget.get_active()
            if index >= 0:
                self.options['size'] = index
                self.set_window_size(self.options['size'])
                self.logger.debug("Window size changed.")

        def on_cbox_modes_changed(widget, data=None):
            index = widget.get_active()
            if index >= 0:
                self.options['mode'] = index
                self.on_change_mode(self.options['mode'])
                self.logger.debug("Key mode changed.")

        def on_cbox_changed(widget, data=None):
            index = widget.get_active()
            name = widget.get_name()
            if index >= 0:
                self.options[name] = index
                self.logger.debug("Window position changed.")

        def on_entry_hotkey_changed(widget, data=None):
            self.options['hotkey'] = widget.get_text()
            self.logger.debug("Hotkey value Changed")

        frm_main = gtk.Frame(_("Preferences"))
        frm_main.set_border_width(6)
        vbox_main = gtk.VBox()

        frm_time = gtk.Frame(_("<b>Time</b>"))
        frm_time.set_border_width(4)
        frm_time.get_label_widget().set_use_markup(True)
        frm_time.set_shadow_type(gtk.SHADOW_NONE)
        hbox_time = gtk.HBox()
        lbl_time1 = gtk.Label(_("Display for"))
        lbl_time2 = gtk.Label(_("seconds"))
        sb_time = gtk.SpinButton(digits=1)
        sb_time.set_increments(0.5, 1.0)
        sb_time.set_range(0.5, 10.0)
        sb_time.set_numeric(True)
        sb_time.set_update_policy(gtk.UPDATE_IF_VALID)
        sb_time.set_value(self.options['timeout'])
        sb_time.connect("value-changed", on_sb_time_changed)
        hbox_time.pack_start(lbl_time1, expand=False, 
                             fill=False, padding=6)
        hbox_time.pack_start(sb_time, expand=False, 
                             fill=False, padding=4)
        hbox_time.pack_start(lbl_time2, expand=False, 
                             fill=False, padding=4)
        frm_time.add(hbox_time)
        frm_time.show_all()

        frm_aspect = gtk.Frame(_("<b>Aspect</b>"))
        frm_aspect.set_border_width(4)
        frm_aspect.get_label_widget().set_use_markup(True)
        frm_aspect.set_shadow_type(gtk.SHADOW_NONE)
        vbox_aspect = gtk.VBox(spacing=6)

        hbox1_aspect = gtk.HBox()

        lbl_positions = gtk.Label(_("Position"))
        cbox_positions = gtk.combo_box_new_text()
        cbox_positions.set_name('position')
        for key, value in self.POSITIONS.items():
            cbox_positions.insert_text(key, value)
        cbox_positions.set_active(self.options['position'])
        cbox_positions.connect("changed", on_cbox_changed)

        hbox1_aspect.pack_start(lbl_positions, expand=False, 
                                fill=False, padding=6)
        hbox1_aspect.pack_start(cbox_positions, expand=False, 
                                fill=False, padding=4)

        hbox2_aspect = gtk.HBox()

        lbl_sizes = gtk.Label(_("Size"))
        cbox_sizes = gtk.combo_box_new_text()
        cbox_sizes.set_name('size')
        for key, value in self.SIZES.items():
            cbox_sizes.insert_text(key, value)
        cbox_sizes.set_active(self.options['size'])
        cbox_sizes.connect("changed", on_cbox_sizes_changed)

        hbox2_aspect.pack_start(lbl_sizes, expand=False, 
                                fill=False, padding=6)
        hbox2_aspect.pack_start(cbox_sizes, expand=False, 
                                fill=False, padding=4)

        vbox_aspect.pack_start(hbox1_aspect)
        vbox_aspect.pack_start(hbox2_aspect)
        frm_aspect.add(vbox_aspect)

        frm_kbd = gtk.Frame(_("<b>Keys</b>"))
        frm_kbd.set_border_width(4)
        frm_kbd.get_label_widget().set_use_markup(True)
        frm_kbd.set_shadow_type(gtk.SHADOW_NONE)
        hbox_kbd = gtk.HBox()
        lbl_kbd = gtk.Label(_("Mode"))
        cbox_modes = gtk.combo_box_new_text()
        cbox_modes.set_name('mode')
        for key, value in self.MODES.items():
            cbox_modes.insert_text(key, value)
        cbox_modes.set_active(self.options['mode'])
        cbox_modes.connect("changed", on_cbox_modes_changed)
        hbox_kbd.pack_start(lbl_kbd, expand=False, 
                            fill=False, padding=6)
        hbox_kbd.pack_start(cbox_modes, expand=False, 
                            fill=False, padding=4)
        frm_kbd.add(hbox_kbd)

        frm_hotkey = gtk.Frame(_("<b>Hot Keys</b>"))
        frm_hotkey.set_border_width(4)
        frm_hotkey.get_label_widget().set_use_markup(True)
        frm_hotkey.set_shadow_type(gtk.SHADOW_NONE)
        hbox_hotkey = gtk.HBox()
        lbl_hotkey = gtk.Label(_("Shortcut"))
        entry_hotkey = gtk.Entry()
        entry_hotkey.set_text(self.options['hotkey'])
        entry_hotkey.set_width_chars(10)
        entry_hotkey.connect("changed", on_entry_hotkey_changed)
        hbox_hotkey.pack_start(lbl_hotkey, expand=False,
                            fill=False, padding=6)
        hbox_hotkey.pack_start(entry_hotkey, expand=False,
                            fill=False, padding=4)
        frm_hotkey.add(hbox_hotkey)


        vbox_main.pack_start(frm_time, False, False, 6)
        vbox_main.pack_start(frm_aspect, False, False, 6)
        vbox_main.pack_start(frm_kbd, False, False, 6)
        vbox_main.pack_start(frm_hotkey, False, False, 6)
        frm_main.add(vbox_main)

        prefs.vbox.pack_start(frm_main)
        prefs.set_destroy_with_parent(True)
        prefs.set_resizable(False)
        prefs.set_has_separator(False)
        prefs.set_default_response(gtk.RESPONSE_CLOSE)
        prefs.vbox.show_all()
        response = prefs.run()
        if response:
            self.store_state(self.options)
        prefs.destroy()

    def on_about_dialog(self, widget, data=None):
        about = gtk.AboutDialog()
        about.set_program_name(APP_NAME)
        about.set_version(VERSION)
        about.set_copyright(u"2010 \u00a9 %s" % AUTHOR)
        about.set_comments(APP_DESC)
        about.set_documenters(
                [u"Jos\xe9 Mar\xeda Quiroga <*****@*****.**>"]
        )
        about.set_website(APP_URL)
        about.set_icon_name('preferences-desktop-keyboard-shortcuts')
        about.set_logo_icon_name(
                'preferences-desktop-keyboard-shortcuts'
        )
        about.run()
        about.destroy()

    def drop_tty(self):
        # We fork and setsid so that we drop the controlling
        # tty.
        if os.fork() != 0:
            os._exit(0)

        os.setsid()
Exemple #10
0
    def __init__(self, logger, nodetach, nohide, bg, fg, size, nosudo, window_id):
        gtk.Window.__init__(self)
        self.timer = None
        self.logger = logger

        self.options = self.load_state()
        if not self.options:
            self.options = {
                'timeout': 2.5,
                'position': POS_BOTTOM,
                'size': size,
                'mode': MODE_NORMAL,
                }

        if not nodetach:
            self.logger.debug("Detach from the parent.")
            self.drop_tty()

        self.set_skip_taskbar_hint(True)
        self.set_skip_pager_hint(True)
        self.set_keep_above(True)
        self.set_decorated(False)
        self.stick()
        self.set_property('accept-focus', False)
        self.set_property('focus-on-map', False)
        self.set_position(gtk.WIN_POS_CENTER)
        bgcolor = gtk.gdk.color_parse(bg)
        self.modify_bg(gtk.STATE_NORMAL, bgcolor)
        self.set_opacity(0.7)

        self.fg = fg

        self.pos_x = 0
        self.pos_y = 0

        gobject.signal_new("text-changed", gtk.Label, 
                        gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ())
        self.label = gtk.Label()
        self.label.set_justify(gtk.JUSTIFY_RIGHT)
        self.label.set_ellipsize(pango.ELLIPSIZE_START)
        self.label.connect("text-changed", self.on_label_change)
        self.label.show()
        self.add(self.label)

        self.screen_width = gtk.gdk.screen_width()   
        self.screen_height = gtk.gdk.screen_height() 

        self.set_gravity(gtk.gdk.GRAVITY_CENTER)

        if window_id == 0:
            self.set_xy_position(self.options['position'])
            self.set_window_size(self.options['size'])
        else:
            other_win_pos = self.get_window_pos(window_id)

            window_width, window_height = self.set_window_size_of_other_win(
                    other_win_pos, self.options['size'])

            self.set_xy_position_of_other_win(other_win_pos, self.options['position'], 
                    window_width, window_height)

        self.nosudo = nosudo

        self.listenkbd = ListenKbd(self.label, logger=self.logger, 
                                   mode=self.options['mode'],
                                   nosudo=self.nosudo)
        self.listenkbd.start()


        menu = gtk.Menu()

        show_item = gtk.CheckMenuItem(_("Show keys"))
        show_item.set_active(True)
        show_item.connect("toggled", self.on_show_keys)
        show_item.show()
        menu.append(show_item)

        preferences_item = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
        preferences_item.connect("activate", self.on_preferences_dialog)
        preferences_item.show()
        menu.append(preferences_item)


        about_item = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
        about_item.connect("activate", self.on_about_dialog)
        about_item.show()
        menu.append(about_item)

        separator_item = gtk.SeparatorMenuItem()
        separator_item.show()
        menu.append(separator_item)

        image = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        image.connect("activate", self.quit)
        image.show()
        menu.append(image)
        menu.show()

        try:
            import appindicator
            self.systray = appindicator.Indicator(APP_NAME, 
                           'indicator-messages', 
                            appindicator.CATEGORY_APPLICATION_STATUS)
            self.systray.set_status(appindicator.STATUS_ACTIVE)
            self.systray.set_attention_icon("indicator-messages-new")
            self.systray.set_icon(
                    "preferences-desktop-keyboard-shortcuts")
            self.systray.set_menu(menu)
            self.logger.debug("Using AppIndicator.")
        except(ImportError):
            self.systray = gtk.StatusIcon()
            self.systray.set_from_icon_name(
                    "preferences-desktop-keyboard-shortcuts")
            self.systray.connect("popup-menu", 
                    self.on_statusicon_popup, menu)
            self.logger.debug("Using StatusIcon.")


        self.connect("destroy-event", self.quit)
        self.connect("delete-event", self.quit)
        self.connect("configure-event", self.on_configure)

        self.no_hide = nohide
        if nohide:
            self.show()
Exemple #11
0
class Screenkey(gtk.Window):

    POSITIONS = {
        POS_TOP:_('Top'),
        POS_CENTER:_('Center'),
        POS_BOTTOM:_('Bottom'),
        POS_KEEP:_('Keep'),
    }
    SIZES = {
        SIZE_LARGE:_('Large'),
        SIZE_MEDIUM:_('Medium'),
        SIZE_SMALL:_('Small'),
    }
    MODES = {
        MODE_RAW:_('Raw'),
        MODE_NORMAL:_('Normal'),
    }

    STATE_FILE = os.path.join(glib.get_user_cache_dir(), 
                              'screenkey.dat')

    def __init__(self, logger, nodetach, nohide, bg, fg, size, nosudo, window_id):
        gtk.Window.__init__(self)
        self.timer = None
        self.logger = logger

        self.options = self.load_state()
        if not self.options:
            self.options = {
                'timeout': 2.5,
                'position': POS_BOTTOM,
                'size': size,
                'mode': MODE_NORMAL,
                }

        if not nodetach:
            self.logger.debug("Detach from the parent.")
            self.drop_tty()

        self.set_skip_taskbar_hint(True)
        self.set_skip_pager_hint(True)
        self.set_keep_above(True)
        self.set_decorated(False)
        self.stick()
        self.set_property('accept-focus', False)
        self.set_property('focus-on-map', False)
        self.set_position(gtk.WIN_POS_CENTER)
        bgcolor = gtk.gdk.color_parse(bg)
        self.modify_bg(gtk.STATE_NORMAL, bgcolor)
        self.set_opacity(0.7)

        self.fg = fg

        self.pos_x = 0
        self.pos_y = 0

        gobject.signal_new("text-changed", gtk.Label, 
                        gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ())
        self.label = gtk.Label()
        self.label.set_justify(gtk.JUSTIFY_RIGHT)
        self.label.set_ellipsize(pango.ELLIPSIZE_START)
        self.label.connect("text-changed", self.on_label_change)
        self.label.show()
        self.add(self.label)

        self.screen_width = gtk.gdk.screen_width()   
        self.screen_height = gtk.gdk.screen_height() 

        self.set_gravity(gtk.gdk.GRAVITY_CENTER)

        if window_id == 0:
            self.set_xy_position(self.options['position'])
            self.set_window_size(self.options['size'])
        else:
            other_win_pos = self.get_window_pos(window_id)

            window_width, window_height = self.set_window_size_of_other_win(
                    other_win_pos, self.options['size'])

            self.set_xy_position_of_other_win(other_win_pos, self.options['position'], 
                    window_width, window_height)

        self.nosudo = nosudo

        self.listenkbd = ListenKbd(self.label, logger=self.logger, 
                                   mode=self.options['mode'],
                                   nosudo=self.nosudo)
        self.listenkbd.start()


        menu = gtk.Menu()

        show_item = gtk.CheckMenuItem(_("Show keys"))
        show_item.set_active(True)
        show_item.connect("toggled", self.on_show_keys)
        show_item.show()
        menu.append(show_item)

        preferences_item = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
        preferences_item.connect("activate", self.on_preferences_dialog)
        preferences_item.show()
        menu.append(preferences_item)


        about_item = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
        about_item.connect("activate", self.on_about_dialog)
        about_item.show()
        menu.append(about_item)

        separator_item = gtk.SeparatorMenuItem()
        separator_item.show()
        menu.append(separator_item)

        image = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        image.connect("activate", self.quit)
        image.show()
        menu.append(image)
        menu.show()

        try:
            import appindicator
            self.systray = appindicator.Indicator(APP_NAME, 
                           'indicator-messages', 
                            appindicator.CATEGORY_APPLICATION_STATUS)
            self.systray.set_status(appindicator.STATUS_ACTIVE)
            self.systray.set_attention_icon("indicator-messages-new")
            self.systray.set_icon(
                    "preferences-desktop-keyboard-shortcuts")
            self.systray.set_menu(menu)
            self.logger.debug("Using AppIndicator.")
        except(ImportError):
            self.systray = gtk.StatusIcon()
            self.systray.set_from_icon_name(
                    "preferences-desktop-keyboard-shortcuts")
            self.systray.connect("popup-menu", 
                    self.on_statusicon_popup, menu)
            self.logger.debug("Using StatusIcon.")


        self.connect("destroy-event", self.quit)
        self.connect("delete-event", self.quit)
        self.connect("configure-event", self.on_configure)

        self.no_hide = nohide
        if nohide:
            self.show()

    def quit(self, widget, data=None):
        try:
            self.listenkbd.stop()
        finally:
            gtk.main_quit()

    def load_state(self):
        """Load stored options"""
        options = None
        try:
            f = open(self.STATE_FILE, 'r')
            try:
                options = pickle.load(f)
                self.logger.debug("Options loaded.")
            except:
                f.close()
        except IOError:
            self.logger.debug("file %s does not exists." % 
                              self.STATE_FILE)
        return options

    def store_state(self, options):
        """Store options"""
        try:
            f = open(self.STATE_FILE, 'w')
            try:
                pickle.dump(options, f)
                self.logger.debug("Options saved.")
            except:
                f.close()
        except IOError:
            self.logger.debug("Cannot open %s." % self.STATE_FILE)

    def set_window_size_of_other_win(self, window_pos, setting):
        """Set window and label size."""
        window_width = int(window_pos['width'] * 0.8)
        window_height = -1

        if setting == SIZE_LARGE:
            window_height = 24 * self.screen_height / 100
        if setting == SIZE_MEDIUM:
            window_height = 12 * self.screen_height / 100
        if setting == SIZE_SMALL:
            window_height = 1 * self.screen_height / 100

        self.resize(window_width, window_height)
        return window_width, window_height

    def set_window_size(self, setting):
        """Set window and label size."""
        window_width = self.screen_width
        window_height = -1

        if setting == SIZE_LARGE:
            window_height = 24 * self.screen_height / 100
        if setting == SIZE_MEDIUM:
            window_height = 12 * self.screen_height / 100
        if setting == SIZE_SMALL:
            window_height = 4 * self.screen_height / 100

        self.resize(window_width, window_height)

    def get_window_pos(self, win_id):
        """ get window position x,y and size width, height" """
        p = Popen(["xwininfo", "-id", win_id], stdout=PIPE)
        out = p.communicate()[0]
        #if p.returncode != 0:
        x = int(re.search("Absolute upper-left X:.*?(\d+)", out).groups()[0])
        y = int(re.search("Absolute upper-left Y:.*?(\d+)", out).groups()[0])
        width = int(re.search("Width:.*?(\d+)", out).groups()[0])
        height = int(re.search("Height:.*?(\d+)", out).groups()[0])

        return {'x': x, 'y': y, 'width': width, 'height': height}

    def set_xy_position_of_other_win(self, window_pos, setting,
            window_width, window_height):
        """Set window position."""

        if setting == POS_TOP:
            self.move(0, window_pos['height'] * 2)
        if setting == POS_CENTER:
            self.move(0, self.screen_height / 2)
        if setting == POS_BOTTOM:
            self.move(window_pos['x']+window_pos['width']-window_width, 
                    int(window_pos['y'] + window_pos['height'] - \
                            window_height*5 - window_pos['height']*0.05))
        if setting == POS_KEEP:
            self.move(self.pos_x, self.pos_y)

    def set_xy_position(self, setting):
        """Set window position."""
        window_width, window_height = self.get_size()
        if setting == POS_TOP:
            self.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DOCK)
            self.move(0, 0)
        if setting == POS_CENTER:
            self.move(0, self.screen_height / 2)
        if setting == POS_BOTTOM:
            self.move(0, self.screen_height - window_height * 2)
        if setting == POS_KEEP:
            self.move(self.pos_x, self.pos_y)

    def on_statusicon_popup(self, widget, button, timestamp, data=None):
        if button == 3:
            if data:
                data.show()
                data.popup(None, None, gtk.status_icon_position_menu, 
                           3, timestamp, widget)

    def on_label_change(self, widget, data=None):
        if not self.get_property('visible'):
            gtk.gdk.threads_enter()
            self.set_xy_position(self.options['position'])
            self.stick()
            self.show()
            gtk.gdk.threads_leave()
        if self.timer:
            self.timer.cancel()

        self.timer = Timer(self.options['timeout'], self.on_timeout)
        self.timer.start()

    def on_timeout(self):
        gtk.gdk.threads_enter()
        if not self.no_hide:
            self.hide()
        self.label.set_text("")
        gtk.gdk.threads_leave()

    def on_change_mode(self, mode):
        self.listenkbd.stop()
        self.listenkbd = ListenKbd(self.label, logger=self.logger, 
                                   mode=mode, nosudo=self.nosudo)
        self.listenkbd.start()

    def on_show_keys(self, widget, data=None):
        if widget.get_active():
            self.logger.debug("Screenkey enabled.")
            self.listenkbd = ListenKbd(self.label, logger=self.logger, 
                                       mode=self.options['mode'],
                                       nosudo=self.nosudo)
            self.listenkbd.start()
        else:
            self.logger.debug("Screenkey disabled.")
            self.listenkbd.stop()

    def on_configure(self, _, event):
        window_height = event.height
        attr = pango.AttrList()
        attr.change(pango.AttrSize((
                    50 * window_height / 100) * 1000, 0, -1))
        attr.change(pango.AttrFamily("Sans", 0, -1))
        attr.change(pango.AttrWeight(pango.WEIGHT_BOLD, 0, -1))

        fgcolor = gtk.gdk.color_parse(self.fg)
        attr.change(pango.AttrForeground(fgcolor.red, fgcolor.green, fgcolor.blue, 0, -1))

        self.pos_x = event.x
        self.pos_y = event.y

        if self.timer:
            self.timer.cancel()

        self.timer = Timer(self.options['timeout'], self.on_timeout)
        self.timer.start()

        self.label.set_attributes(attr)

    def on_preferences_dialog(self, widget, data=None):
        prefs = gtk.Dialog(APP_NAME, None, 
                    gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, 
                    (gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE))

        def on_sb_time_changed(widget, data=None):
            self.options['timeout'] = widget.get_value()
            self.logger.debug("Timeout value changed.")

        def on_cbox_sizes_changed(widget, data=None):
            index = widget.get_active()
            if index >= 0:
                self.options['size'] = index
                self.set_window_size(self.options['size'])
                self.logger.debug("Window size changed.")

        def on_cbox_modes_changed(widget, data=None):
            index = widget.get_active()
            if index >= 0:
                self.options['mode'] = index
                self.on_change_mode(self.options['mode'])
                self.logger.debug("Key mode changed.")

        def on_cbox_changed(widget, data=None):
            index = widget.get_active()
            name = widget.get_name()
            if index >= 0:
                self.options[name] = index
                self.logger.debug("Window position changed.")

        frm_main = gtk.Frame(_("Preferences"))
        frm_main.set_border_width(6)
        vbox_main = gtk.VBox()

        frm_time = gtk.Frame(_("<b>Time</b>"))
        frm_time.set_border_width(4)
        frm_time.get_label_widget().set_use_markup(True)
        frm_time.set_shadow_type(gtk.SHADOW_NONE)
        hbox_time = gtk.HBox()
        lbl_time1 = gtk.Label(_("Display for"))
        lbl_time2 = gtk.Label(_("seconds"))
        sb_time = gtk.SpinButton(digits=1)
        sb_time.set_increments(0.5, 1.0)
        sb_time.set_range(0.5, 10.0)
        sb_time.set_numeric(True)
        sb_time.set_update_policy(gtk.UPDATE_IF_VALID)
        sb_time.set_value(self.options['timeout'])
        sb_time.connect("value-changed", on_sb_time_changed)
        hbox_time.pack_start(lbl_time1, expand=False, 
                             fill=False, padding=6)
        hbox_time.pack_start(sb_time, expand=False, 
                             fill=False, padding=4)
        hbox_time.pack_start(lbl_time2, expand=False, 
                             fill=False, padding=4)
        frm_time.add(hbox_time)
        frm_time.show_all()

        frm_aspect = gtk.Frame(_("<b>Aspect</b>"))
        frm_aspect.set_border_width(4)
        frm_aspect.get_label_widget().set_use_markup(True)
        frm_aspect.set_shadow_type(gtk.SHADOW_NONE)
        vbox_aspect = gtk.VBox(spacing=6)

        hbox1_aspect = gtk.HBox()

        lbl_positions = gtk.Label(_("Position"))
        cbox_positions = gtk.combo_box_new_text()
        cbox_positions.set_name('position')
        for key, value in self.POSITIONS.items():
            cbox_positions.insert_text(key, value)
        cbox_positions.set_active(self.options['position'])
        cbox_positions.connect("changed", on_cbox_changed)

        hbox1_aspect.pack_start(lbl_positions, expand=False, 
                                fill=False, padding=6)
        hbox1_aspect.pack_start(cbox_positions, expand=False, 
                                fill=False, padding=4)

        hbox2_aspect = gtk.HBox()

        lbl_sizes = gtk.Label(_("Size"))
        cbox_sizes = gtk.combo_box_new_text()
        cbox_sizes.set_name('size')
        for key, value in self.SIZES.items():
            cbox_sizes.insert_text(key, value)
        cbox_sizes.set_active(self.options['size'])
        cbox_sizes.connect("changed", on_cbox_sizes_changed)

        hbox2_aspect.pack_start(lbl_sizes, expand=False, 
                                fill=False, padding=6)
        hbox2_aspect.pack_start(cbox_sizes, expand=False, 
                                fill=False, padding=4)

        vbox_aspect.pack_start(hbox1_aspect)
        vbox_aspect.pack_start(hbox2_aspect)
        frm_aspect.add(vbox_aspect)

        frm_kbd = gtk.Frame(_("<b>Keys</b>"))
        frm_kbd.set_border_width(4)
        frm_kbd.get_label_widget().set_use_markup(True)
        frm_kbd.set_shadow_type(gtk.SHADOW_NONE)
        hbox_kbd = gtk.HBox()
        lbl_kbd = gtk.Label(_("Mode"))
        cbox_modes = gtk.combo_box_new_text()
        cbox_modes.set_name('mode')
        for key, value in self.MODES.items():
            cbox_modes.insert_text(key, value)
        cbox_modes.set_active(self.options['mode'])
        cbox_modes.connect("changed", on_cbox_modes_changed)
        hbox_kbd.pack_start(lbl_kbd, expand=False, 
                            fill=False, padding=6)
        hbox_kbd.pack_start(cbox_modes, expand=False, 
                            fill=False, padding=4)
        frm_kbd.add(hbox_kbd)

        vbox_main.pack_start(frm_time, False, False, 6)
        vbox_main.pack_start(frm_aspect, False, False, 6)
        vbox_main.pack_start(frm_kbd, False, False, 6)
        frm_main.add(vbox_main)

        prefs.vbox.pack_start(frm_main)
        prefs.set_destroy_with_parent(True)
        prefs.set_resizable(False)
        prefs.set_has_separator(False)
        prefs.set_default_response(gtk.RESPONSE_CLOSE)
        prefs.vbox.show_all()
        response = prefs.run()
        if response:
            self.store_state(self.options)
        prefs.destroy()

    def on_about_dialog(self, widget, data=None):
        about = gtk.AboutDialog()
        about.set_program_name(APP_NAME)
        about.set_version(VERSION)
        about.set_copyright(u"2010 \u00a9 %s" % AUTHOR)
        about.set_comments(APP_DESC)
        about.set_documenters(
                [u"Jos\xe9 Mar\xeda Quiroga <*****@*****.**>"]
        )
        about.set_website(APP_URL)
        about.set_icon_name('preferences-desktop-keyboard-shortcuts')
        about.set_logo_icon_name(
                'preferences-desktop-keyboard-shortcuts'
        )
        about.run()
        about.destroy()

    def drop_tty(self):
        # We fork and setsid so that we drop the controlling
        # tty.
        if os.fork() != 0:
            os._exit(0)

        os.setsid()
Exemple #12
0
    def __init__(self, logger, nodetach, timeout, size, mode, position, opacity, bgcolor, font#, color):
            ):
        gtk.Window.__init__(self)

        self.timer = None
        self.logger = logger

        self.options = {
                'timeout': timeout,
                'size': size,
                'mode': mode,
                'position': position,
                'opacity': opacity,
                'bgcolor': bgcolor,
                'font': font,
                'color': #color
                         [65535, 65535, 65535, 0, -1]
                }

        if not nodetach:
            self.logger.debug("Detach from the parent.")
            self.drop_tty()

        self.set_skip_taskbar_hint(True)
        self.set_skip_pager_hint(True)
        self.set_keep_above(True)
        self.set_decorated(False)
        self.stick()
        self.set_property('accept-focus', False)
        self.set_property('focus-on-map', False)
        self.set_position(gtk.WIN_POS_CENTER)
        bgcolor = gtk.gdk.color_parse(self.options['bgcolor'])
        self.modify_bg(gtk.STATE_NORMAL, bgcolor)
        self.set_opacity(self.options['opacity'])

        gobject.signal_new("text-changed", gtk.Label, 
                        gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ())
        self.label = gtk.Label()
        self.label.set_justify(gtk.JUSTIFY_RIGHT)
        self.label.set_ellipsize(pango.ELLIPSIZE_START)
        self.label.connect("text-changed", self.on_label_change)
        self.label.show()
        self.add(self.label)

        self.screen_width = gtk.gdk.screen_width()
        self.screen_height = gtk.gdk.screen_height()
        self.set_window_size(self.options['size'])

        self.set_gravity(gtk.gdk.GRAVITY_CENTER)
        self.set_xy_position(self.options['position'])

        self.listenkbd = ListenKbd(self.label, logger=self.logger, 
                                   mode=self.options['mode'])
        self.listenkbd.start()


        menu = gtk.Menu()

        show_item = gtk.CheckMenuItem(_("Show keys"))
        show_item.set_active(True)
        show_item.connect("toggled", self.on_show_keys)
        show_item.show()
        menu.append(show_item)

        preferences_item = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
        preferences_item.connect("activate", self.on_preferences_dialog)
        preferences_item.show()
        menu.append(preferences_item)


        about_item = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
        about_item.connect("activate", self.on_about_dialog)
        about_item.show()
        menu.append(about_item)

        separator_item = gtk.SeparatorMenuItem()
        separator_item.show()
        menu.append(separator_item)

        image = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        image.connect("activate", self.quit)
        image.show()
        menu.append(image)
        menu.show()

        try:
            import appindicator
            self.systray = appindicator.Indicator(APP_NAME, 
                           'indicator-messages', 
                            appindicator.CATEGORY_APPLICATION_STATUS)
            self.systray.set_status(appindicator.STATUS_ACTIVE)
            self.systray.set_attention_icon("indicator-messages-new")
            self.systray.set_icon(
                    "preferences-desktop-keyboard-shortcuts")
            self.systray.set_menu(menu)
            self.logger.debug("Using AppIndicator.")
        except(ImportError):
            self.systray = gtk.StatusIcon()
            self.systray.set_from_icon_name(
                    "preferences-desktop-keyboard-shortcuts")
            self.systray.connect("popup-menu", 
                    self.on_statusicon_popup, menu)
            self.logger.debug("Using StatusIcon.")


        self.connect("delete-event", self.quit)