Example #1
0
def cb_any_event(event, onboard):
    # Update layout on keyboard group changes
    # XkbStateNotify maps to Gdk.EventType.NOTHING
    # https://bugzilla.gnome.org/show_bug.cgi?id=156948

    # Hide bug in Oneirics GTK3
    # Suppress ValueError: invalid enum value: 4294967295
    type = None
    try:
        type = event.type
    except ValueError:
        pass

    if 0:  # debug
        a = [event, event.type]
        if type == Gdk.EventType.VISIBILITY_NOTIFY:
            a += [event.state]
        if type == Gdk.EventType.CONFIGURE:
            a += [event.x, event.y, event.width, event.height]
        print(*a)

    if type == Gdk.EventType.NOTHING:
        onboard.reload_layout()

    elif type == Gdk.EventType.SETTING:
        if event.setting.name == "gtk-theme-name":
            onboard.on_gtk_theme_changed()
        elif event.setting.name in ["gtk-xft-dpi", "gtk-xft-antialias" "gtk-xft-hinting", "gtk-xft-hintstyle"]:
            # Update the cached pango layout object here or Onboard
            # doesn't get those settings, in particular the font dpi.
            # For some reason the font sizes are still off when running
            # this immediately. Delay it a little.
            GObject.idle_add(onboard.on_gtk_font_dpi_changed)

    Gtk.main_do_event(event)
 def start(self):
     self.connect("destroy", Gtk.main_quit)
     self.set_position(Gtk.WindowPosition.CENTER)
     self.show_all()
     GObject.threads_init()
     Gtk.main()
     return self.accepted
Example #3
0
    def on_locale_changed(self, obj):
        """ Fired when the locale is changed on the first view. """

        if self.is_building:
            return

        loc = self.get_selected_locale()
        if not loc:
            return

        # Display warning if self.savespace_activated
        if self.savespace_activated:
            GObject.idle_add(self.main_window.set_sensitive, False)
            GObject.idle_add(self.savespace_disabled_dialog.show)

            # We need to set the keyboard layout!
        lay = loc.split(".")[0].split("@")[0].split("_")[1].lower()
        # We will use idle_add otherwise GUI will freeze for a few seconds (it should rebuild all layouts).
        GObject.idle_add(self.populate_layout_model, lay)

        # Set the variant too, if any
        var = loc.split(".")[0].split("@")[0].split("_")[0].lower()
        # We will use idle_add otherwise GUI will freeze for a few seconds (it should rebuild all layouts).
        GObject.idle_add(self.populate_variant_model, None, var)

        # We need to set the timezone!
        tzone = loc.split(".")[0].split("@")[0].split("_")[1].upper()
        if tzone in tzone_countries:
            # We will use idle_add otherwise GUI will freeze for a few seconds (it should rebuild all timezones).
            GObject.idle_add(self.populate_timezone_model, tzone_countries[tzone])
Example #4
0
def enterNonblockingMode():
    global conn, log

    log.debug("entering nonblocking-mode")
    conn.setblocking(False)
    GObject.io_add_watch(conn, GObject.IO_IN, on_data, [""])
    GObject.idle_add(on_loop)
Example #5
0
    def register_gtk_quit(self):
        window = self.get_widget(self.gtkbuilder_id)
        self.do_gtk_quit = True

        # This means we've already been closed
        if window is None:
            gobject.idle_add(gtk.main_quit)
Example #6
0
    def _move(self, up=False):
        text = self._search_entry.get_text()
        if not text:
            return

        if up and self.__selected_search_result == 1:
            return False

        model = self._treeview.get_model()
        selection = self._treeview.get_selection()
        # disable flush timeout while searching
        if self._entry_flush_timeout:
            GObject.source_remove(self._entry_flush_timeout)
            self._entry_flush_timeout = 0
        # search
        start_count = self.__selected_search_result + (-1 if up else 1)
        start_iter = model.get_iter_first()
        found_iter = self.search_iter(selection, start_iter, text, 0, start_count)
        if found_iter:
            self.__selected_search_result += -1 if up else 1
            return True
        else:
            # Return to old iter
            self.search_iter(selection, start_iter, text, 0, self.__selected_search_result)
            return False
        # renew flush timeout
        self._renew_flush_timeout()
        return
Example #7
0
    def _import_gst(self):
        """Import the necessary GObject-related modules and assign `Gst`
        and `GObject` fields on this object.
        """

        try:
            import gi
        except ImportError:
            raise FatalReplayGainError("Failed to load GStreamer: python-gi not found")

        try:
            gi.require_version("Gst", "1.0")
        except ValueError as e:
            raise FatalReplayGainError("Failed to load GStreamer 1.0: {0}".format(e))

        from gi.repository import GObject, Gst, GLib

        # Calling GObject.threads_init() is not needed for
        # PyGObject 3.10.2+
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            GObject.threads_init()
        Gst.init([sys.argv[0]])

        self.GObject = GObject
        self.GLib = GLib
        self.Gst = Gst
Example #8
0
def main():
    win = Gtk.Window()
    win.connect("destroy", lambda w: Gtk.main_quit())
    win.set_default_size(800, 650)

    global graph, sim, pwm

    vbox = Gtk.VBox()
    win.add(vbox)

    graph = Graph()
    vbox.pack_start(graph, True, True, 0)

    hbox = Gtk.HBox()
    plusbtn = Gtk.Button("+")
    plusbtn.connect("clicked", addpwm)
    hbox.pack_start(plusbtn, True, True, 0)
    minbtn = Gtk.Button("-")
    minbtn.connect("clicked", subtractpwm)
    hbox.pack_start(minbtn, True, True, 0)
    pwm = add_label("pwm: ", hbox)

    vbox.pack_start(hbox, False, False, 0)
    sim = Simulator()

    GObject.timeout_add(5, callback)

    win.show_all()
    Gtk.main()

    print "bye!"
Example #9
0
    def __init__(self, window):
        """Class initialiser"""
        if isinstance(window.get_child(), Gtk.Notebook):
            err("There is already a Notebook at the top of this window")
            raise (ValueError)

        Container.__init__(self)
        GObject.GObject.__init__(self)
        self.terminator = Terminator()
        self.window = window
        GObject.type_register(Notebook)
        self.register_signals(Notebook)
        self.connect("switch-page", self.deferred_on_tab_switch)
        self.configure()

        child = window.get_child()
        window.remove(child)
        window.add(self)
        window_last_active_term = window.last_active_term
        self.newtab(widget=child)
        if window_last_active_term:
            self.set_last_active_term(window_last_active_term)
            window.last_active_term = None

        self.show_all()
Example #10
0
def main():
    GObject.threads_init()
    app = TerminalWin()

    keybinding = GlobalKeyBinding()
    app.keybinding = keybinding
    ConfigManager.ref_keybinding = keybinding
    ConfigManager.ref_show_hide = app.show_hide
    keybinding.connect("activate", lambda w: app.show_hide())
    if not keybinding.grab():
        ConfigManager.set_conf("losefocus-hiding", "False")
        ConfigManager.set_conf("hide-on-start", "False")
        app.update_ui()
        msgtext = (
            "Another application using '%s'. Please open preferences and change the shortcut key."
            % ConfigManager.get_conf("global-key")
        )
        msgbox = Gtk.MessageDialog(
            app, Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK, msgtext
        )
        msgbox.run()
        msgbox.destroy()
    else:
        keybinding.start()
    Gtk.main()
Example #11
0
    def __init__(self, parent, service, ok_cb, err_cb):
        self.parent = parent
        self.ok_cb = ok_cb
        self.err_cb = err_cb

        self.device = None
        self.connection = None

        parent.bus.add_signal_receiver(self.on_nm_device_added, "DeviceAdded", "org.freedesktop.NetworkManager")
        parent.bus.add_signal_receiver(self.on_nma_new_connection, "NewConnection", self.parent.settings_interface)

        self.device = self.parent.find_device(service.device.Address)

        self.connection = self.parent.find_connection(service.device.Address, "panu")
        if not self.connection:
            # This is for compatibility with network-manager < 0.9.8.6. Newer versions that support BlueZ 5 add a
            # default connection automatically
            addr_bytes = bytearray.fromhex(str.replace(str(service.device.Address), ":", " "))
            parent.nma.AddConnection(
                {
                    "connection": {
                        "id": "%s on %s" % (service.name, service.device.Alias),
                        "uuid": str(uuid1()),
                        "autoconnect": False,
                        "type": "bluetooth",
                    },
                    "bluetooth": {"bdaddr": dbus.ByteArray(addr_bytes), "type": "panu"},
                    "ipv4": {"method": "auto"},
                    "ipv6": {"method": "auto"},
                }
            )
            GObject.timeout_add(1000, self.signal_wait_timeout)
        else:
            self.init_connection()
    def stop_animation(self, *args):
        self.animating = False
        if self.timer:
            GObject.source_remove(self.timer)
            self.timer = None

        self.drawing.queue_draw()
Example #13
0
def _check_videosink():
    from gi.repository import Gst
    from gi.repository import Gdk
    from gi.repository import GObject

    global videosink_factory

    try:
        # If using GdkBroadwayDisplay make sure not to try to use gtkglsink
        # as it would segfault right away.
        if GObject.type_is_a(Gdk.Display.get_default().__gtype__, GObject.type_from_name("GdkBroadwayDisplay")):
            videosink_factory = Gst.ElementFactory.find("gtksink")
            return True
    except RuntimeError:
        pass

    if "gtkglsink" in os.environ.get("PITIVI_UNSTABLE_FEATURES", ""):
        sink = Gst.ElementFactory.make("gtkglsink", None)
        if not sink:
            videosink_factory = sink.get_factory()
        elif sink.set_state(Gst.State.READY) == Gst.StateChangeReturn.SUCCESS:
            videosink_factory = sink.get_factory()
            sink.set_state(Gst.State.NULL)
        else:
            videosink_factory = Gst.ElementFactory.find("gtksink")
    else:
        videosink_factory = Gst.ElementFactory.find("gtksink")

    if videosink_factory:
        return True

    return False
Example #14
0
File: view.py Project: keekun/Hotot
 def on_load_finish(self, view, webframe):
     if self.load_finish_flag:
         return
     self.load_finish_flag = True
     agent.webv = self
     # overlay extra variables of web part
     variables = {
         "platform": "Linux",
         "conf_dir": config.CONF_DIR,
         "cache_dir": config.CACHE_DIR,
         "avatar_cache_dir": config.AVATAR_CACHE_DIR,
         "extra_fonts": utils.get_extra_fonts(),
         "extra_exts": utils.get_extra_exts(),
         "extra_themes": utils.get_extra_themes(),
         "locale": utils.get_locale(),
     }
     # and then, notify web part i am ready to work :)
     GObject.idle_add(
         view.execute_script,
         """
         overlay_variables(%s);
         globals.load_flags = 1;
         """
         % json.dumps(variables),
     )
Example #15
0
    def __init__(self, window):
        Gtk.Dialog.__init__(
            self, _("Edit archive"), window, Gtk.DialogFlags.MODAL, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL)
        )
        self.kill = False  # Dialog is killed.
        self.file_handler = window.file_handler
        self._window = window
        self._save_button = self.add_button(Gtk.STOCK_SAVE_AS, Gtk.ResponseType.OK)
        # There is no stock response for "import", but by using
        # RESPONSE_HELP we automatically get the button placed at the left.
        self._import_button = self.add_button(_("Import"), Gtk.ResponseType.HELP)
        self._import_button.set_image(Gtk.Image.new_from_stock(Gtk.STOCK_ADD, Gtk.IconSize.BUTTON))
        self.set_border_width(4)
        self.resize(
            min(Gdk.Screen.get_default().get_width() - 50, 750), min(Gdk.Screen.get_default().get_height() - 50, 600)
        )
        self.connect("response", self._response)

        self._image_area = _ImageArea(self)
        self._other_area = _OtherArea(self)

        notebook = Gtk.Notebook()
        notebook.set_border_width(6)
        notebook.append_page(self._image_area, Gtk.Label(label=_("Images")))
        notebook.append_page(self._other_area, Gtk.Label(label=_("Other files")))
        self.vbox.pack_start(notebook, True, True, 0)
        self.show_all()
        GObject.idle_add(self._load_original_files)
Example #16
0
 def on_tab_switch(self, notebook, page, page_num, data=None):
     """Do the real work for a tab switch"""
     tabs_last_active_term = data["tabs_last_active_term"]
     if tabs_last_active_term:
         term = self.terminator.find_terminal_by_uuid(tabs_last_active_term.urn)
         GObject.idle_add(term.ensure_visible_and_focussed)
     return True
Example #17
0
 def get_key(self, line):
     logging.debug("got a key press")
     logging.debug("line: %s" % line)
     code, count, cmd, device = line.split(" ")[:4]
     timestamp = self.last_ts
     previous_key = self.last_key
     self.last_key = cmd
     self.last_ts = time.time()
     if count != "0":
         logging.debug("repeated keypress")
         return
     elif self.last_ts - timestamp < self.delta_t and self.last_key == previous_key:
         logging.debug("ignoring keypress within min_delta")
         return
     else:
         try:
             logging.debug("remove main.timer")
             GObject.source_remove(self.main.timer)
         except:
             logging.debug("could not remove timer")
     logging.debug("Key press: %s", cmd)
     logging.debug("current frontend: %s", self.main.current)
     if self.main.current == "vdr":
         self.vdr_key_action(code, count, cmd, device)
     elif self.main.current == "kodi":
         self.kodi_key_action(code, count, cmd, device)
     else:
         logging.debug("keypress for other frontend")
         logging.debug("current frontend is: %s" % self.main.current)
         logging.debug("vdrStatus is: %s" % self.main.vdrStatus)
         logging.debug("frontend status is: %s" % self.main.status())
Example #18
0
    def add_notification(self, icon, corner=Gtk.CornerType.TOP_LEFT, duration=_NOTIFICATION_DURATION):

        if not isinstance(icon, NotificationIcon):
            raise TypeError("icon must be a NotificationIcon.")

        window = NotificationWindow()

        screen = Gdk.Screen.get_default()
        if corner == Gtk.CornerType.TOP_LEFT:
            window.move(0, 0)
        elif corner == Gtk.CornerType.TOP_RIGHT:
            window.move(screen.get_width() - style.GRID_CELL_SIZE, 0)
        elif corner == Gtk.CornerType.BOTTOM_LEFT:
            window.move(0, screen.get_height() - style.GRID_CELL_SIZE)
        elif corner == Gtk.CornerType.BOTTOM_RIGHT:
            window.move(screen.get_width() - style.GRID_CELL_SIZE, screen.get_height() - style.GRID_CELL_SIZE)
        else:
            raise ValueError("Inalid corner: %r" % corner)

        window.add(icon)
        icon.show()
        window.show()

        self._notif_by_icon[icon] = window

        GObject.timeout_add(duration, lambda: self.remove_notification(icon))
Example #19
0
    def _all_clear(self):
        """ Things to reinitialize when starting up a new game. """
        if self._timeout_id is not None:
            GObject.source_remove(self._timeout_id)

        # Auto advance levels
        if self._correct > 3 and self._level < len(self._dots):
            self._level += 3
            self._correct = 0

        self._set_label("")
        for i in range(3):
            self._opts[i].hide()
            self._opts[i].type = -1
            self._opts[i].set_label("")

        for dot in self._dots:
            dot.type = -1
            if self._game == 2 or self._dots.index(dot) < self._level:
                dot.set_shape(self._new_dot_surface(self._colors[abs(dot.type)]))
                dot.set_label("?")
                dot.set_layer(100)
            else:
                dot.hide()

        self._dance_counter = 0
        self._dance_step()
Example #20
0
    def start_ponder(self, pondermove, movelist, cmove):

        startpos = gv.gshogi.get_startpos()

        # if not startpos must be sfen
        if startpos != "startpos":
            startpos = "sfen " + startpos

        ml = ""
        for move in movelist:
            ml = ml + move + " "
        # if ml == "":
        #    print "error empty movelist in ponder in usi.py"
        #    return

        ml = ml.strip()
        ml = ml + " " + cmove + " " + pondermove
        ml = ml.strip()

        # create the position string with the ponder move added
        b = "position " + startpos + " moves " + ml + "\n"

        # Send the board position to the engine
        self.command(b)

        pondercmd = "go ponder" + self.gocmnd[2:]
        self.command(pondercmd + "\n")

        # clear the engine output window ready for next move
        GObject.idle_add(self.engine_output.clear, self.side, self.get_running_engine().strip())

        return
Example #21
0
def auto_connect_by_name(callback_obj, builder):
    """finds handlers like on_<widget_name>_<signal> and connects them

    i.e. find widget,signal pair in builder and call
    widget.connect(signal, on_<widget_name>_<signal>)"""

    callback_handler_dict = dict_from_callback_obj(callback_obj)

    for item in builder.widgets.items():
        (widget_name, widget) = item
        signal_ids = []
        try:
            widget_type = type(widget)
            while widget_type:
                signal_ids.extend(GObject.signal_list_ids(widget_type))
                widget_type = GObject.type_parent(widget_type)
        except RuntimeError:  # pylint wants a specific error
            pass
        signal_names = [GObject.signal_name(sid) for sid in signal_ids]

        # Now, automatically find any the user didn't specify in glade
        for sig in signal_names:
            # using convention suggested by glade
            sig = sig.replace("-", "_")
            handler_names = ["on_%s_%s" % (widget_name, sig)]

            # Using the convention that the top level window is not
            # specified in the handler name. That is use
            # on_destroy() instead of on_windowname_destroy()
            if widget is callback_obj:
                handler_names.append("on_%s" % sig)

            do_connect(item, sig, handler_names, callback_handler_dict, builder.connections)

    log_unconnected_functions(callback_handler_dict, builder.connections)
Example #22
0
 def setModel(self, model):
     self.model = model
     self.model.connect("time_changed", self.time_changed)
     self.model.connect("player_changed", self.player_changed)
     self.formatedCache = [formatTime(self.model.getPlayerTime(self.model.movingColor or WHITE))] * 2
     if model.secs != 0 or model.gain != 0:
         GObject.timeout_add(100, self.update)
Example #23
0
    def __init__(self, oneconfviewpickler):
        """Controller of the installed pane"""

        LOG.debug("OneConf Handler init")
        super(OneConfHandler, self).__init__()

        # FIXME: should be an enum common to OneConf and here
        self.appname = "Ubuntu Software Center"

        # OneConf stuff
        self.oneconf = DbusConnect()
        self.oneconf.hosts_dbus_object.connect_to_signal("hostlist_changed", self.refresh_hosts)
        self.oneconf.hosts_dbus_object.connect_to_signal("packagelist_changed", self._on_store_packagelist_changed)
        self.oneconf.hosts_dbus_object.connect_to_signal(
            "latestsync_changed", self.on_new_latest_oneconf_sync_timestamp
        )
        self.already_registered_hostids = []
        self.is_current_registered = False

        self.oneconfviewpickler = oneconfviewpickler

        # refresh host list
        self._refreshing_hosts = False
        GObject.timeout_add_seconds(MIN_TIME_WITHOUT_ACTIVITY, self.get_latest_oneconf_sync)
        GObject.idle_add(self.refresh_hosts)
def run():
    # Protobuf
    #c = ControllerProtobuf()

    # Directly connected to the vision server
    c = VisionManager()
    
    if not c.is_connected():
        print("Vision server is not accessible.")
        return

    server = Server()
    server.start("127.0.0.1", 5030)

    # add observer output for "server"
    c.add_filter_output_observer(server.send)

    from gi.repository import Gtk, GObject
    import CapraVision.client.gtk.main
    GObject.threads_init()

    w = CapraVision.client.gtk.main.WinFilterChain(c)

    w.window.show_all()
    Gtk.main()

    # Close connection
    server.stop()
    c.close_server()
Example #25
0
 def pulse(self, owner):
     """Callback to update progress information"""
     if self.transaction.cancelled:
         return False
     self.transaction.progress_details = (
         self.current_items,
         self.total_items,
         self.current_bytes,
         self.total_bytes,
         self.current_cps,
         self.elapsed_time,
     )
     percent = ((self.current_bytes + self.current_items) * 100.0) / float(self.total_bytes + self.total_items)
     progress = int(self.progress_begin + percent / 100 * (self.progress_end - self.progress_begin))
     # If the progress runs backwards emit an illegal progress value
     # e.g. during cache updates.
     if self.progress > progress:
         self.transaction.progress = 101
     else:
         self.transaction.progress = progress
         self.progress = progress
     # Show all currently downloaded files
     items = []
     for worker in owner.workers:
         if not worker.current_item:
             continue
         self._emit_acquire_item(worker.current_item, worker.total_size, worker.current_size)
         items.append(worker.current_item)
     self._emit_status_details(items)
     while GObject.main_context_default().pending():
         GObject.main_context_default().iteration()
     return True
Example #26
0
    def set_value(self, match_image, value):
        logging.debug("assigning %s to %s" % (value, self.name))
        logging.debug("%s needs a %s" % (self.name, self.prop.value_type))

        # blob-ize
        if GObject.type_is_a(self.prop.value_type, vips_type_blob):
            if not isinstance(value, Vips.Blob):
                value = Vips.Blob.new(None, value)

        # image-ize
        if GObject.type_is_a(self.prop.value_type, vips_type_image):
            if not isinstance(value, Vips.Image):
                value = imageize(match_image, value)

        # array-ize some types, if necessary
        value = arrayize(self.prop.value_type, value)

        # MODIFY input images need to be copied before assigning them
        if self.flags & Vips.ArgumentFlags.MODIFY:
            # don't use .copy(): we want to make a new pipeline with no
            # reference back to the old stuff ... this way we can free the
            # previous image earlier
            logging.debug("MODIFY argument: copying image")
            new_image = Vips.Image.new_memory()
            value.write(new_image)
            value = new_image

        logging.debug("assigning %s" % value)

        self.op.props.__setattr__(self.name, value)
Example #27
0
 def listener(self, sock, *args):
     """Asynchronous connection listener. Starts a handler for each connection."""
     conn, temp = sock.accept()
     loggy.log("Connected from " + str(conn.getsockname()))
     GObject.io_add_watch(conn, GObject.IO_IN, self.handler)
     conn.send("OK MPD 0.16.0\n")
     return True
Example #28
0
 def stop(self):
     if self._pulse_hid is not None:
         GObject.source_remove(self._pulse_hid)
         self._pulse_hid = None
     self._icon.xo_color = self._icon.get_base_color()
     self._phase = 0
     self._icon.alpha = 1.0
Example #29
0
    def on_savespace_no(self, obj):
        """ Triggered when the No button has been pressed on the savespace dialog. """

        self.purge_older_translations = False

        GObject.idle_add(self.main_window.set_sensitive, True)
        GObject.idle_add(self.savespace_dialog.hide)
Example #30
0
 def __notify_cb(self, device, name):
     """Defer response to notifications; they arrive in a burst,
     but without any indication that the burst is complete, so we
     use a timeout to respond."""
     if self._timeout_sid:
         GObject.source_remove(self._timeout_sid)
     self._timeout_sid = GObject.timeout_add(100, self.__timeout_cb)