Exemplo n.º 1
0
def check_bluetooth_status(message, exitfunc, *args, **kwargs):
    try:
        applet = AppletService()
    except DBusProxyFailed as e:
        logging.exception(e)
        print("Blueman applet needs to be running")
        exitfunc()
    if "PowerManager" in applet.QueryPlugins():
        if not applet.get_bluetooth_status():

            d = Gtk.MessageDialog(None, type=Gtk.MessageType.ERROR)
            d.props.icon_name = "blueman"
            d.props.text = _("Bluetooth Turned Off")
            d.props.secondary_text = message

            d.add_button("Exit", Gtk.ResponseType.NO)
            d.add_button(_("Enable Bluetooth"), Gtk.ResponseType.YES)
            resp = d.run()
            d.destroy()
            if resp != Gtk.ResponseType.YES:
                exitfunc()
            else:
                applet.SetBluetoothStatus('(b)', True, **kwargs)
                if not applet.get_bluetooth_status():
                    print('Failed to enable bluetooth')
                    exitfunc()
Exemplo n.º 2
0
    def __init__(self, blueman):
        super(ManagerDeviceMenu, self).__init__()
        self.set_name("ManagerDeviceMenu")
        self.Blueman = blueman
        self.SelectedDevice = None

        self.is_popup = False

        self._device_property_changed_signal = self.Blueman.List.connect(
            "device-property-changed", self.on_device_property_changed)
        self._selection_done_signal = None

        ManagerDeviceMenu.__instances__.append(self)

        self._any_network = AnyNetwork()
        self._any_network.connect_signal('property-changed',
                                         self._on_service_property_changed)

        self._any_device = AnyDevice()
        self._any_device.connect_signal('property-changed',
                                        self._on_service_property_changed)

        try:
            self._appl = AppletService()
        except DBusProxyFailed:
            logging.error("** Failed to connect to applet", exc_info=True)
            self._appl = None

        self.generate()
Exemplo n.º 3
0
        def on_dbus_name_appeared(_connection, name, owner):
            logging.info("%s %s" % (name, owner))
            setup_icon_path()

            try:
                self.Applet = AppletService()
            except DBusProxyFailed:
                print("Blueman applet needs to be running")
                exit()

            check_bluetooth_status(_("Bluetooth needs to be turned on for the device manager to function"),
                                   lambda: Gtk.main_quit())

            try:
                bluez.Manager().get_adapter(self.Config['last-adapter'])
            except bluez.errors.DBusNoSuchAdapterError:
                logging.error('No bluetooth adapter(s) found.')
                exit(1)

            self._applet_sig = self.Applet.connect('g-signal', on_applet_signal)

            self.connect("delete-event", on_window_delete)
            self.props.icon_name = "blueman"

            w, h, x, y = self.Config["window-properties"]
            if w and h:
                self.resize(w, h)
            if x and y:
                self.move(x, y)

            sw = self.Builder.get_object("scrollview")
            # Disable overlay scrolling
            if Gtk.get_minor_version() >= 16:
                sw.props.overlay_scrolling = False

            self.List = ManagerDeviceList(adapter=self.Config["last-adapter"], inst=self)

            self.List.show()
            sw.add(self.List)

            self.Toolbar = ManagerToolbar(self)
            self.Menu = ManagerMenu(self)
            self.Stats = ManagerStats(self)

            if self.List.is_valid_adapter():
                self.List.display_known_devices(autoselect=True)

            self.List.connect("adapter-changed", self.on_adapter_changed)

            toolbar = self.Builder.get_object("toolbar")
            statusbar = self.Builder.get_object("statusbar")

            self.Config.bind_to_widget("show-toolbar", toolbar, "visible")
            self.Config.bind_to_widget("show-statusbar", statusbar, "visible")

            self.show()
Exemplo n.º 4
0
    def __init__(self):
        check_single_instance("blueman-tray")

        applet = AppletService()

        main_loop = GLib.MainLoop()

        Gio.bus_watch_name(Gio.BusType.SESSION, 'org.blueman.Applet',
                           Gio.BusNameWatcherFlags.NONE, None,
                           lambda _connection, _name: main_loop.quit())

        indicator_name = applet.GetStatusIconImplementation()
        logging.info('Using indicator "%s"' % indicator_name)
        indicator_class = getattr(
            import_module('blueman.main.indicators.' + indicator_name),
            indicator_name)
        self.indicator = indicator_class(applet.GetIconName(),
                                         self._activate_menu_item,
                                         self._activate_status_icon)

        applet.connect('g-signal', self.on_signal)

        self.indicator.set_text(applet.GetText())
        self.indicator.set_visibility(applet.GetVisibility())
        self.indicator.set_menu(applet.GetMenu())

        main_loop.run()
Exemplo n.º 5
0
            def on_dbus_name_appeared(_connection: Gio.DBusConnection,
                                      name: str, owner: str) -> None:
                logging.info(f"{name} {owner}")
                setup_icon_path()

                try:
                    self.Applet = AppletService()
                except DBusProxyFailed:
                    print("Blueman applet needs to be running")
                    bmexit()

                check_bluetooth_status(
                    _("Bluetooth needs to be turned on for the device manager to function"
                      ), lambda: self.quit())

                manager = Manager()
                try:
                    manager.get_adapter(self.Config['last-adapter'])
                except DBusNoSuchAdapterError:
                    logging.error(
                        'Default adapter not found, trying first available.')
                    try:
                        manager.get_adapter(None)
                    except DBusNoSuchAdapterError:
                        logging.error('No adapter(s) found, exiting')
                        bmexit()

                self._applethandlerid = self.Applet.connect(
                    'g-signal', on_applet_signal)

                sw = self.builder.get_widget("scrollview", Gtk.ScrolledWindow)
                # Disable overlay scrolling
                if Gtk.get_minor_version() >= 16:
                    sw.props.overlay_scrolling = False

                self.List = ManagerDeviceList(
                    adapter=self.Config["last-adapter"], inst=self)

                self.List.show()
                sw.add(self.List)

                self.Toolbar = ManagerToolbar(self)
                self.Menu = ManagerMenu(self)
                self.Stats = ManagerStats(self)

                if self.List.is_valid_adapter():
                    self.List.populate_devices()

                self.List.connect("adapter-changed", self.on_adapter_changed)

                self.Config.bind_to_widget("show-toolbar", toolbar, "visible")
                self.Config.bind_to_widget("show-statusbar", statusbar,
                                           "visible")
Exemplo n.º 6
0
    def on_load(self, container: Gtk.Box) -> None:

        self._builder = Builder("services-transfer.ui")
        self.widget = self._builder.get_widget("transfer", Gtk.Widget)

        container.pack_start(self.widget, True, True, 0)
        a = AppletService()
        if "TransferService" in a.QueryPlugins():
            self._setup_transfer()
        else:
            self.widget.props.sensitive = False
            self.widget.props.tooltip_text = _(
                "Applet's transfer service plugin is disabled")
Exemplo n.º 7
0
        def on_dbus_name_appeared(_connection, name, owner):
            logging.info("%s %s" % (name, owner))
            setup_icon_path()

            try:
                self.Applet = AppletService()
            except DBusProxyFailed:
                print("Blueman applet needs to be running")
                exit()

            if 'PowerManager' in self.Applet.QueryPlugins():
                if not self.Applet.get_bluetooth_status():
                    bt_status_changed(False)

            self._applet_sig = self.Applet.connect('g-signal', on_applet_signal)

            self.connect("delete-event", on_window_delete)
            self.props.icon_name = "blueman"

            w, h, x, y = self.Config["window-properties"]
            if w and h:
                self.resize(w, h)
            if x and y:
                self.move(x, y)

            sw = self.Builder.get_object("scrollview")
            # Disable overlay scrolling
            if Gtk.get_minor_version() >= 16:
                sw.props.overlay_scrolling = False

            self.List = ManagerDeviceList(adapter=self.Config["last-adapter"], inst=self)

            self.List.show()
            sw.add(self.List)

            self.Toolbar = ManagerToolbar(self)
            self.Menu = ManagerMenu(self)
            self.Stats = ManagerStats(self)

            if self.List.is_valid_adapter():
                self.List.display_known_devices(autoselect=True)

            self.List.connect("adapter-changed", self.on_adapter_changed)

            toolbar = self.Builder.get_object("toolbar")
            statusbar = self.Builder.get_object("statusbar")

            self.Config.bind_to_widget("show-toolbar", toolbar, "visible")
            self.Config.bind_to_widget("show-statusbar", statusbar, "visible")

            self.show()
Exemplo n.º 8
0
    def on_load(self, container: Gtk.Box) -> None:

        self.Builder = Gtk.Builder()
        self.Builder.set_translation_domain("blueman")
        self.Builder.add_from_file(UI_PATH + "/services-transfer.ui")
        self.widget = self.Builder.get_object("transfer")

        container.pack_start(self.widget, True, True, 0)
        a = AppletService()
        if "TransferService" in a.QueryPlugins():
            self._setup_transfer()
        else:
            self.widget.props.sensitive = False
            self.widget.props.tooltip_text = _("Applet's transfer service plugin is disabled")
Exemplo n.º 9
0
    def _on_name_appeared(self, _connection: Gio.DBusConnection, name: str, _owner: str) -> None:
        logging.debug("Applet started on name %s, showing indicator" % name)

        applet = AppletService()
        indicator_name = applet.GetStatusIconImplementation()
        logging.info(f'Using indicator "{indicator_name}"')
        indicator_class = getattr(import_module('blueman.main.indicators.' + indicator_name), indicator_name)
        self.indicator = indicator_class(applet.GetIconName(), self._activate_menu_item, self._activate_status_icon)

        applet.connect('g-signal', self.on_signal)

        self.indicator.set_text(applet.GetText())
        self.indicator.set_visibility(applet.GetVisibility())
        self.indicator.set_menu(applet.GetMenu())

        self._active = True
Exemplo n.º 10
0
def check_bluetooth_status(message, exitfunc, *args, **kwargs):
    try:
        applet = AppletService()
    except DBusProxyFailed as e:
        logging.exception(e)
        print("Blueman applet needs to be running")
        exitfunc()
    if "PowerManager" in applet.QueryPlugins():
        if not applet.get_bluetooth_status():

            d = Gtk.MessageDialog(None, type=Gtk.MessageType.ERROR)
            d.props.icon_name = "blueman"
            d.props.text = _("Bluetooth Turned Off")
            d.props.secondary_text = message

            d.add_button("Exit", Gtk.ResponseType.NO)
            d.add_button(_("Enable Bluetooth"), Gtk.ResponseType.YES)
            resp = d.run()
            d.destroy()
            if resp != Gtk.ResponseType.YES:
                exitfunc()
            else:
                applet.SetBluetoothStatus('(b)', True, **kwargs)
                if not applet.get_bluetooth_status():
                    print('Failed to enable bluetooth')
                    exitfunc()
Exemplo n.º 11
0
def check_bluetooth_status(message, exitfunc):
    try:
        applet = AppletService()
    except DBusProxyFailed as e:
        logging.exception(e)
        print("Blueman applet needs to be running")
        exitfunc()
        return

    if "PowerManager" not in applet.QueryPlugins():
        return

    if not applet.GetBluetoothStatus():
        d = Gtk.MessageDialog(None,
                              type=Gtk.MessageType.ERROR,
                              icon_name="blueman",
                              text=_("Bluetooth Turned Off"),
                              secondary_text=message)
        d.add_button(_("Exit"), Gtk.ResponseType.NO)
        d.add_button(_("Enable Bluetooth"), Gtk.ResponseType.YES)

        resp = d.run()
        d.destroy()

        if resp != Gtk.ResponseType.YES:
            exitfunc()
            return

    applet.SetBluetoothStatus('(b)', True)

    timeout = time() + 60
    while applet.GetRequestStatus():
        sleep(0.1)
        if time() > timeout:
            break

    if not applet.GetBluetoothStatus():
        print('Failed to enable bluetooth')
        exitfunc()
        return

    config = Config("org.blueman.plugins.powermanager")
    if config["auto-power-on"] is None:
        d = Gtk.MessageDialog(
            None,
            type=Gtk.MessageType.QUESTION,
            icon_name="blueman",
            text=_("Shall bluetooth get enabled automatically?"))
        d.add_button(_("Yes"), Gtk.ResponseType.YES)
        d.add_button(_("No"), Gtk.ResponseType.NO)

        resp = d.run()
        d.destroy()

        config["auto-power-on"] = resp == Gtk.ResponseType.YES
Exemplo n.º 12
0
    def __init__(self):
        check_single_instance("blueman-tray")

        applet = AppletService()

        main_loop = GLib.MainLoop()

        Gio.bus_watch_name(Gio.BusType.SESSION, 'org.blueman.Applet',
                           Gio.BusNameWatcherFlags.NONE, None, lambda _connection, _name: main_loop.quit())

        indicator_name = applet.GetStatusIconImplementation()
        logging.info('Using indicator "%s"' % indicator_name)
        indicator_class = getattr(import_module('blueman.main.indicators.' + indicator_name), indicator_name)
        self.indicator = indicator_class(applet.GetIconName(), self._activate_menu_item, self._activate_status_icon)

        applet.connect('g-signal', self.on_signal)

        self.indicator.set_text(applet.GetText())
        self.indicator.set_visibility(applet.GetVisibility())
        self.indicator.set_menu(applet.GetMenu())

        main_loop.run()
Exemplo n.º 13
0
    def _on_name_appeared(self, _connection: Gio.DBusConnection, name: str, _owner: str) -> None:
        logging.debug("Applet started on name %s, showing indicator" % name)

        applet = AppletService()
        for indicator_name in applet.GetStatusIconImplementations():
            indicator_class = getattr(import_module('blueman.main.indicators.' + indicator_name), indicator_name)
            try:
                self.indicator = indicator_class(
                    applet.GetIconName(), self._activate_menu_item, self._activate_status_icon)
                break
            except IndicatorNotAvailable:
                logging.info(f'Indicator "{indicator_name}" is not available')
        logging.info(f'Using indicator "{self.indicator.__class__.__name__}"')

        applet.connect('g-signal', self.on_signal)

        self.indicator.set_tooltip_title(applet.GetToolTipTitle())
        self.indicator.set_tooltip_text(applet.GetToolTipText())
        self.indicator.set_visibility(applet.GetVisibility())
        self.indicator.set_menu(applet.GetMenu())

        self._active = True
Exemplo n.º 14
0
class Blueman(Gtk.Window):
    def __init__(self):
        super().__init__(title=_("Bluetooth Devices"))

        self._applet_sig = None

        self.Config = Config("org.blueman.general")

        self.Builder = Gtk.Builder()
        self.Builder.set_translation_domain("blueman")
        #        bind_textdomain_codeset("blueman", "UTF-8")
        self.Builder.add_from_file(UI_PATH + "/manager-main.ui")

        grid = self.Builder.get_object("grid")
        self.add(grid)
        self.set_name("BluemanManager")

        self.Plugins = PluginManager(ManagerPlugin, blueman.plugins.manager,
                                     self)
        self.Plugins.load_plugin()

        area = MessageArea()
        grid.attach(area, 0, 3, 1, 1)

        # Add margin for resize grip or it will overlap
        if self.get_has_resize_grip():
            statusbar = self.Builder.get_object("statusbar")
            margin_right = statusbar.get_margin_right()
            statusbar.set_margin_right(margin_right + 10)

        def do_present(time):
            if self.props.visible:
                self.present_with_time(time)

        check_single_instance("blueman-manager", do_present)

        def on_window_delete(window, event):
            w, h = self.get_size()
            x, y = self.get_position()
            self.Config["window-properties"] = [w, h, x, y]
            Gtk.main_quit()

        def bt_status_changed(status):
            if not status:
                self.hide()
                check_bluetooth_status(
                    _("Bluetooth needs to be turned on for the device manager to function"
                      ), lambda: Gtk.main_quit())
            else:
                self.show()

        def on_applet_signal(_proxy, _sender, signal_name, params):
            if signal_name == 'BluetoothStatusChanged':
                status = params.unpack()
                bt_status_changed(status)

        def on_dbus_name_vanished(_connection, name):
            logging.info(name)
            if self._applet_sig is not None:
                self.Applet.disconnect(self._applet_sig)
                self._applet_sig = None

            self.hide()

            d = ErrorDialog(
                _("Connection to BlueZ failed"),
                _("Bluez daemon is not running, blueman-manager cannot continue.\n"
                  "This probably means that there were no Bluetooth adapters detected "
                  "or Bluetooth daemon was not started."),
                icon_name="blueman")
            d.run()
            d.destroy()

            # FIXME ui can handle BlueZ start/stop but we should inform user
            Gtk.main_quit()

        def on_dbus_name_appeared(_connection, name, owner):
            logging.info("%s %s" % (name, owner))
            setup_icon_path()

            try:
                self.Applet = AppletService()
            except DBusProxyFailed:
                print("Blueman applet needs to be running")
                exit()

            check_bluetooth_status(
                _("Bluetooth needs to be turned on for the device manager to function"
                  ), lambda: Gtk.main_quit())

            manager = bluez.Manager()
            try:
                manager.get_adapter(self.Config['last-adapter'])
            except bluez.errors.DBusNoSuchAdapterError:
                logging.error(
                    'Default adapter not found, trying first available.')
                try:
                    manager.get_adapter(None)
                except bluez.errors.DBusNoSuchAdapterError:
                    logging.error('No adapter(s) found, exiting')
                    exit(1)

            self._applet_sig = self.Applet.connect('g-signal',
                                                   on_applet_signal)

            self.connect("delete-event", on_window_delete)
            self.props.icon_name = "blueman"

            w, h, x, y = self.Config["window-properties"]
            if w and h:
                self.resize(w, h)
            if x and y:
                self.move(x, y)

            sw = self.Builder.get_object("scrollview")
            # Disable overlay scrolling
            if Gtk.get_minor_version() >= 16:
                sw.props.overlay_scrolling = False

            self.List = ManagerDeviceList(adapter=self.Config["last-adapter"],
                                          inst=self)

            self.List.show()
            sw.add(self.List)

            self.Toolbar = ManagerToolbar(self)
            self.Menu = ManagerMenu(self)
            self.Stats = ManagerStats(self)

            if self.List.is_valid_adapter():
                self.List.display_known_devices(autoselect=True)

            self.List.connect("adapter-changed", self.on_adapter_changed)

            toolbar = self.Builder.get_object("toolbar")
            statusbar = self.Builder.get_object("statusbar")

            self.Config.bind_to_widget("show-toolbar", toolbar, "visible")
            self.Config.bind_to_widget("show-statusbar", statusbar, "visible")

            self.show()

        bluez.Manager.watch_name_owner(on_dbus_name_appeared,
                                       on_dbus_name_vanished)

    def on_adapter_changed(self, lst, adapter):
        if adapter is not None:
            self.List.display_known_devices(autoselect=True)

    def inquiry(self):
        def prop_changed(lst, adapter, key_value):
            key, value = key_value
            if key == "Discovering" and not value:
                prog.finalize()
                self.List.disconnect(s1)
                self.List.disconnect(s2)

        def on_progress(lst, frac):
            if abs(1.0 - frac) <= 0.00001:
                if not prog.started():
                    prog.start()
            else:
                prog.fraction(frac)

        prog = ManagerProgressbar(self, text=_("Searching"))
        prog.connect("cancelled", lambda x: self.List.stop_discovery())
        try:
            self.List.discover_devices()
        except Exception as e:
            prog.finalize()
            MessageArea.show_message(*e_(e))

        s1 = self.List.connect("discovery-progress", on_progress)
        s2 = self.List.connect("adapter-property-changed", prop_changed)

    def setup(self, device):
        command = "blueman-assistant --device=%s" % device['Address']
        launch(command, None, False, "blueman", _("Bluetooth Assistant"))

    def bond(self, device):
        def error_handler(e):
            logging.exception(e)
            message = 'Pairing failed for:\n%s (%s)' % (device['Alias'],
                                                        device['Address'])
            Notification('Bluetooth', message, icon_name="blueman").show()

        device.pair(error_handler=error_handler)

    def adapter_properties(self):
        launch("blueman-adapters", None, False, "blueman",
               _("Adapter Preferences"))

    def toggle_trust(self, device):
        device['Trusted'] = not device['Trusted']

    def send(self, device, f=None):
        adapter = self.List.Adapter

        command = "blueman-sendto --source=%s --device=%s" % (
            adapter["Address"], device['Address'])
        launch(command, None, False, "blueman", _("File Sender"))

    def remove(self, device):
        self.List.Adapter.remove_device(device)
Exemplo n.º 15
0
    def on_request_menu_items(
            self, manager_menu: ManagerDeviceMenu,
            device: Device) -> List[Tuple[Gtk.MenuItem, int]]:
        items: List[Tuple[Gtk.MenuItem, int]] = []
        appl = AppletService()

        self.has_dun = False
        serial_items: List[Gtk.MenuItem] = []

        def add_menu_item(manager_menu: ManagerDeviceMenu,
                          service: Service) -> None:
            if service.connected:
                surface = self._make_x_icon(service.icon, 16)
                item = create_menuitem(service.name, surface=surface)
                item.connect("activate", manager_menu.on_disconnect, service)
                items.append((item, service.priority + 100))
            else:
                item = create_menuitem(service.name, service.icon)
                if service.description:
                    item.props.tooltip_text = service.description
                item.connect("activate", manager_menu.on_connect, service)
                if isinstance(service, SerialService):
                    serial_items.append(item)
                    if isinstance(service, DialupNetwork):
                        self.has_dun = True
                else:
                    items.append((item, service.priority))
            item.props.sensitive = service.available
            item.show()

        for service in get_services(device):
            add_menu_item(manager_menu, service)

            if isinstance(service, SerialService):
                for dev in rfcomm_list():
                    if dev["dst"] == device['Address'] and dev[
                            "state"] == "connected":
                        devname = _("Serial Port %s") % "rfcomm%d" % dev["id"]

                        surface = self._make_x_icon("modem", 16)
                        item: Gtk.MenuItem = create_menuitem(devname,
                                                             surface=surface)
                        item.connect("activate", manager_menu.on_disconnect,
                                     service, dev["id"])
                        items.append((item, 120))
                        item.show()

            if isinstance(service, NetworkService) and service.connected:
                if "DhcpClient" in appl.QueryPlugins():

                    def renew(_item: Gtk.MenuItem) -> None:
                        appl.DhcpClient('(s)', device.get_object_path())

                    item = create_menuitem(_("Renew IP Address"),
                                           "view-refresh")
                    item.connect("activate", renew)
                    item.show()
                    items.append((item, 201))

        if self.has_dun and ('PPPSupport' in appl.QueryPlugins()
                             or 'NMDUNSupport' in appl.QueryPlugins()):

            def open_settings(_item: Gtk.MenuItem, device: Device) -> None:
                from blueman.gui.GsmSettings import GsmSettings

                d = GsmSettings(device['Address'])
                d.run()
                d.destroy()

            item = Gtk.SeparatorMenuItem()
            item.show()
            serial_items.append(item)

            item = create_menuitem(_("Dialup Settings"), "preferences-other")
            serial_items.append(item)
            item.show()
            item.connect("activate", open_settings, device)

        if len(serial_items) > 1:
            sub = Gtk.Menu()
            sub.show()

            item = create_menuitem(_("Serial Ports"), "modem")
            item.set_submenu(sub)
            item.show()
            items.append((item, 90))

            for item in serial_items:
                sub.append(item)
        else:
            for item in serial_items:
                items.append((item, 80))

        return items
Exemplo n.º 16
0
class Blueman(Gtk.Window):
    def __init__(self):
        super(Blueman, self).__init__(title=_("Bluetooth Devices"))

        self._applet_sig = None

        self.Config = Config("org.blueman.general")

        self.Builder = Gtk.Builder()
        self.Builder.set_translation_domain("blueman")
        bind_textdomain_codeset("blueman", "UTF-8")
        self.Builder.add_from_file(UI_PATH + "/manager-main.ui")

        grid = self.Builder.get_object("grid")
        self.add(grid)
        self.set_name("BluemanManager")

        self.Plugins = PluginManager(ManagerPlugin, blueman.plugins.manager, self)
        self.Plugins.load_plugin()

        area = MessageArea()
        grid.attach(area, 0, 3, 1, 1)

        # Add margin for resize grip or it will overlap
        if self.get_has_resize_grip():
            statusbar = self.Builder.get_object("statusbar")
            margin_right = statusbar.get_margin_right()
            statusbar.set_margin_right(margin_right + 10)

        def do_present(time):
            if self.props.visible:
                self.present_with_time(time)

        check_single_instance("blueman-manager", do_present)

        def on_window_delete(window, event):
            w, h = self.get_size()
            x, y = self.get_position()
            self.Config["window-properties"] = [w, h, x, y]
            Gtk.main_quit()

        def bt_status_changed(status):
            if not status:
                self.hide()
                check_bluetooth_status(_("Bluetooth needs to be turned on for the device manager to function"),
                                       lambda: Gtk.main_quit())
            else:
                self.show()

        def on_applet_signal(_proxy, _sender, signal_name, params):
            if signal_name == 'BluetoothStatusChanged':
                status = params.unpack()
                bt_status_changed(status)

        def on_dbus_name_vanished(_connection, name):
            logging.info(name)
            if self._applet_sig is not None:
                self.Applet.disconnect(self._applet_sig)
                self._applet_sig = None

            self.hide()

            d = ErrorDialog(
                _("Connection to BlueZ failed"),
                _("Bluez daemon is not running, blueman-manager cannot continue.\n"
                  "This probably means that there were no Bluetooth adapters detected "
                  "or Bluetooth daemon was not started."),
                icon_name="blueman")
            d.run()
            d.destroy()

            # FIXME ui can handle BlueZ start/stop but we should inform user
            Gtk.main_quit()

        def on_dbus_name_appeared(_connection, name, owner):
            logging.info("%s %s" % (name, owner))
            setup_icon_path()

            try:
                self.Applet = AppletService()
            except DBusProxyFailed:
                print("Blueman applet needs to be running")
                exit()

            if 'PowerManager' in self.Applet.QueryPlugins():
                if not self.Applet.get_bluetooth_status():
                    bt_status_changed(False)

            self._applet_sig = self.Applet.connect('g-signal', on_applet_signal)

            self.connect("delete-event", on_window_delete)
            self.props.icon_name = "blueman"

            w, h, x, y = self.Config["window-properties"]
            if w and h:
                self.resize(w, h)
            if x and y:
                self.move(x, y)

            sw = self.Builder.get_object("scrollview")
            # Disable overlay scrolling
            if Gtk.get_minor_version() >= 16:
                sw.props.overlay_scrolling = False

            self.List = ManagerDeviceList(adapter=self.Config["last-adapter"], inst=self)

            self.List.show()
            sw.add(self.List)

            self.Toolbar = ManagerToolbar(self)
            self.Menu = ManagerMenu(self)
            self.Stats = ManagerStats(self)

            if self.List.is_valid_adapter():
                self.List.display_known_devices(autoselect=True)

            self.List.connect("adapter-changed", self.on_adapter_changed)

            toolbar = self.Builder.get_object("toolbar")
            statusbar = self.Builder.get_object("statusbar")

            self.Config.bind_to_widget("show-toolbar", toolbar, "visible")
            self.Config.bind_to_widget("show-statusbar", statusbar, "visible")

            self.show()

        bluez.Manager.watch_name_owner(on_dbus_name_appeared, on_dbus_name_vanished)

    def on_adapter_changed(self, lst, adapter):
        if adapter is not None:
            self.List.display_known_devices(autoselect=True)

    def inquiry(self):
        def prop_changed(lst, adapter, key_value):
            key, value = key_value
            if key == "Discovering" and not value:
                prog.finalize()
                self.List.disconnect(s1)
                self.List.disconnect(s2)

        def on_progress(lst, frac):
            if abs(1.0 - frac) <= 0.00001:
                if not prog.started():
                    prog.start()
            else:
                prog.fraction(frac)

        prog = ManagerProgressbar(self, text=_("Searching"))
        prog.connect("cancelled", lambda x: self.List.stop_discovery())
        try:
            self.List.discover_devices()
        except Exception as e:
            prog.finalize()
            MessageArea.show_message(*e_(e))

        s1 = self.List.connect("discovery-progress", on_progress)
        s2 = self.List.connect("adapter-property-changed", prop_changed)

    def setup(self, device):
        command = "blueman-assistant --device=%s" % device['Address']
        launch(command, None, False, "blueman", _("Bluetooth Assistant"))

    def bond(self, device):
        def error_handler(e):
            logging.exception(e)
            message = 'Pairing failed for:\n%s (%s)' % (device['Alias'], device['Address'])
            Notification('Bluetooth', message, icon_name="blueman").show()

        device.pair(error_handler=error_handler)

    def adapter_properties(self):
        launch("blueman-adapters", None, False, "blueman", _("Adapter Preferences"))

    def toggle_trust(self, device):
        device['Trusted'] = not device['Trusted']

    def send(self, device, f=None):
        adapter = self.List.Adapter

        command = "blueman-sendto --source=%s --device=%s" % (adapter["Address"], device['Address'])
        launch(command, None, False, "blueman", _("File Sender"))

    def remove(self, device):
        self.List.Adapter.remove_device(device)
Exemplo n.º 17
0
    def setup_network(self):
        self.Config = Config("org.blueman.network")

        nap_enable = self.Builder.get_object("nap-enable")
        r_dnsmasq = self.Builder.get_object("r_dnsmasq")
        r_dhcpd = self.Builder.get_object("r_dhcpd")
        r_udhcpd = self.Builder.get_object("r_udhcpd")
        net_ip = self.Builder.get_object("net_ip")
        rb_nm = self.Builder.get_object("rb_nm")
        rb_blueman = self.Builder.get_object("rb_blueman")
        rb_dun_nm = self.Builder.get_object("rb_dun_nm")
        rb_dun_blueman = self.Builder.get_object("rb_dun_blueman")

        nap_frame = self.Builder.get_object("nap_frame")
        warning = self.Builder.get_object("warning")

        if not self.Config["nap-enable"]:
            nap_frame.props.sensitive = False

        nc = NetConf.get_default()
        if nc.ip4_address is not None:
            net_ip.props.text = inet_ntoa(nc.ip4_address)
            nap_enable.props.active = True
        else:
            net_ip.props.text = "10.%d.%d.1" % (randint(0, 255), randint(0, 255))

        if nc.get_dhcp_handler() is None:
            nap_frame.props.sensitive = False
            nap_enable.props.active = False
            r_dnsmasq.props.active = True
            self.Config["nap-enable"] = False

        have_dhcpd = have("dhcpd3") or have("dhcpd")
        have_dnsmasq = have("dnsmasq")
        have_udhcpd = have("udhcpd")

        if nc.get_dhcp_handler() == DnsMasqHandler and have_dnsmasq:
            r_dnsmasq.props.active = True
        elif nc.get_dhcp_handler() == DhcpdHandler and have_dhcpd:
            r_dhcpd.props.active = True
        elif nc.get_dhcp_handler() == UdhcpdHandler and have_udhcpd:
            r_udhcpd.props.active = True
        else:
            r_dnsmasq.props.active = True

        if not have_dnsmasq and not have_dhcpd and not have_udhcpd:
            nap_frame.props.sensitive = False
            warning.props.visible = True
            warning.props.sensitive = True
            nap_enable.props.sensitive = False
            self.Config["nap-enable"] = False

        if not have_dnsmasq:
            r_dnsmasq.props.sensitive = False
            r_dnsmasq.props.active = False

        if not have_dhcpd:
            r_dhcpd.props.sensitive = False
            r_dhcpd.props.active = False

        if not have_udhcpd:
            r_udhcpd.props.sensitive = False
            r_udhcpd.props.active = False

        r_dnsmasq.connect("toggled", lambda x: self.option_changed_notify("dnsmasq"))
        r_dhcpd.connect("toggled", lambda x: self.option_changed_notify("dhcpd"))
        r_udhcpd.connect("toggled", lambda x: self.option_changed_notify("udhcpd"))

        net_ip.connect("changed", lambda x: self.option_changed_notify("ip", False))
        nap_enable.connect("toggled", lambda x: self.option_changed_notify("nap_enable"))

        self.Config.bind_to_widget("nap-enable", nap_enable, "active", Gio.SettingsBindFlags.GET)

        nap_enable.bind_property("active", nap_frame, "sensitive", 0)

        applet = AppletService()

        avail_plugins = applet.QueryAvailablePlugins()
        active_plugins = applet.QueryPlugins()

        def dun_support_toggled(rb, x):
            if rb.props.active and x == "nm":
                applet.SetPluginConfig('(sb)', "PPPSupport", False)
                applet.SetPluginConfig('(sb)', "NMDUNSupport", True)
            elif rb.props.active and x == "blueman":
                applet.SetPluginConfig('(sb)', "NMDUNSupport", False)
                applet.SetPluginConfig('(sb)', "PPPSupport", True)

        def pan_support_toggled(rb, x):
            if rb.props.active and x == "nm":
                applet.SetPluginConfig('(sb)', "DhcpClient", False)
                applet.SetPluginConfig('(sb)', "NMPANSupport", True)

            elif rb.props.active and x == "blueman":
                applet.SetPluginConfig('(sb)', "NMPANSupport", False)
                applet.SetPluginConfig('(sb)', "DhcpClient", True)

        if "PPPSupport" in active_plugins:
            rb_dun_blueman.props.active = True

        if "NMDUNSupport" in avail_plugins:
            rb_dun_nm.props.sensitive = True
        else:
            rb_dun_nm.props.sensitive = False
            rb_dun_nm.props.tooltip_text = _("Not currently supported with this setup")

        if "DhcpClient" in active_plugins:
            rb_blueman.props.active = True

        if "NMPANSupport" in avail_plugins:
            rb_nm.props.sensitive = True
        else:
            rb_nm.props.sensitive = False
            rb_nm.props.tooltip_text = _("Not currently supported with this setup")

        if "NMPANSupport" in active_plugins:
            rb_nm.props.active = True

        if "NMDUNSupport" in active_plugins:
            rb_dun_nm.props.active = True

        rb_nm.connect("toggled", pan_support_toggled, "nm")
        rb_blueman.connect("toggled", pan_support_toggled, "blueman")

        rb_dun_nm.connect("toggled", dun_support_toggled, "nm")
        rb_dun_blueman.connect("toggled", dun_support_toggled, "blueman")
Exemplo n.º 18
0
    def on_request_menu_items(self, manager_menu: ManagerDeviceMenu,
                              device: Device) -> List[DeviceMenuItem]:
        items: List[DeviceMenuItem] = []
        appl = AppletService()

        services = get_services(device)

        connectable_services = [
            service for service in services if service.connectable
        ]
        for service in connectable_services:
            item: Gtk.MenuItem = create_menuitem(service.name, service.icon)
            if service.description:
                item.props.tooltip_text = service.description
            item.connect(
                "activate", lambda _item: manager_menu.connect_service(
                    service.device, service.uuid))
            items.append(
                DeviceMenuItem(item, DeviceMenuItem.Group.CONNECT,
                               service.priority))
            item.props.sensitive = service.available
            item.show()

        connected_services = [
            service for service in services if service.connected_instances
        ]
        for service in connected_services:
            for instance in service.connected_instances:
                surface = self._make_x_icon(service.icon, 16)
                item = create_menuitem(instance.name, surface=surface)
                item.connect(
                    "activate", lambda _item: manager_menu.disconnect_service(
                        service.device, service.uuid, instance.port))
                items.append(
                    DeviceMenuItem(item, DeviceMenuItem.Group.DISCONNECT,
                                   service.priority + 100))
                item.show()

        if services:
            config = AutoConnectConfig()
            autoconnect_services = set(config["services"])
            for service in services:
                if service.connected_instances or (
                        device.get_object_path(),
                        service.uuid) in autoconnect_services:
                    item = Gtk.CheckMenuItem(label=service.name)
                    config.bind_to_menuitem(item, device, service.uuid)
                    item.show()
                    items.append(
                        DeviceMenuItem(item, DeviceMenuItem.Group.AUTOCONNECT,
                                       service.priority))

        for action, priority in set((action, service.priority)
                                    for service in services
                                    for action in service.common_actions
                                    if any(plugin in appl.QueryPlugins()
                                           for plugin in action.plugins)):
            item = create_menuitem(action.title, action.icon)
            items.append(
                DeviceMenuItem(item, DeviceMenuItem.Group.ACTIONS,
                               priority + 200))
            item.show()
            item.connect("activate",
                         self._get_activation_handler(action.callback))

        return items
Exemplo n.º 19
0
 def _activate_menu_item(self, *indexes: int) -> None:
     AppletService().ActivateMenuItem('(ai)', indexes)
Exemplo n.º 20
0
class Blueman(Gtk.Application):
    def __init__(self) -> None:
        super().__init__(application_id="org.blueman.Manager")

        def do_quit(_: object) -> bool:
            self.quit()
            return False

        s = GLib.unix_signal_source_new(signal.SIGINT)
        s.set_callback(do_quit)
        s.attach()

    window: Optional[Gtk.ApplicationWindow]

    def do_startup(self) -> None:
        def doquit(_a: Gio.SimpleAction, _param: None) -> None:
            self.quit()

        Gtk.Application.do_startup(self)
        self.window = None

        self.Config = Config("org.blueman.general")

        quit_action = Gio.SimpleAction.new("Quit", None)
        quit_action.connect("activate", doquit)
        self.set_accels_for_action("app.Quit", ["<Ctrl>q", "<Ctrl>w"])
        self.add_action(quit_action)

    def do_activate(self) -> None:
        if not self.window:
            self.window = Gtk.ApplicationWindow(application=self,
                                                name="BluemanManager",
                                                icon_name="blueman",
                                                title=_("Bluetooth Devices"))
            w, h, x, y = self.Config["window-properties"]
            if w and h:
                self.window.resize(w, h)
            if x and y:
                self.window.move(x, y)

            # Connect to configure event to store new window position and size
            self.window.connect("configure-event", self._on_configure)

            self.builder = Builder("manager-main.ui")
            box = self.builder.get_widget("box", Gtk.Box)
            self.window.add(box)

            grid = self.builder.get_widget("grid", Gtk.Grid)

            toolbar = self.builder.get_widget("toolbar", Gtk.Toolbar)
            statusbar = self.builder.get_widget("statusbar", Gtk.Box)

            self.Plugins = PluginManager(ManagerPlugin,
                                         blueman.plugins.manager, self)
            self.Plugins.load_plugin()

            area = MessageArea()
            grid.attach(area, 0, 1, 1, 1)

            self._applethandlerid: Optional[int] = None

            # Add margin for resize grip or it will overlap
            if self.window.get_has_resize_grip():
                margin_right = statusbar.get_margin_right()
                statusbar.set_margin_right(margin_right + 10)

            def bt_status_changed(status: bool) -> None:
                assert self.window is not None
                if not status:
                    self.window.hide()
                    check_bluetooth_status(
                        _("Bluetooth needs to be turned on for the device manager to function"
                          ), self.quit)
                else:
                    self.window.show()

            def on_applet_signal(_proxy: AppletService, _sender: str,
                                 signal_name: str,
                                 params: GLib.Variant) -> None:
                if signal_name == 'BluetoothStatusChanged':
                    status = params.unpack()
                    bt_status_changed(status)

            def on_dbus_name_vanished(_connection: Gio.DBusConnection,
                                      name: str) -> None:
                logging.info(name)
                if self._applethandlerid:
                    self.Applet.disconnect(self._applethandlerid)
                    self._applethandlerid = None

                if self.window is not None:
                    self.window.hide()

                d = ErrorDialog(
                    _("Connection to BlueZ failed"),
                    _("Bluez daemon is not running, blueman-manager cannot continue.\n"
                      "This probably means that there were no Bluetooth adapters detected "
                      "or Bluetooth daemon was not started."),
                    icon_name="blueman")
                d.run()
                d.destroy()

                # FIXME ui can handle BlueZ start/stop but we should inform user
                self.quit()

            def on_dbus_name_appeared(_connection: Gio.DBusConnection,
                                      name: str, owner: str) -> None:
                logging.info(f"{name} {owner}")
                setup_icon_path()

                try:
                    self.Applet = AppletService()
                except DBusProxyFailed:
                    print("Blueman applet needs to be running")
                    bmexit()

                check_bluetooth_status(
                    _("Bluetooth needs to be turned on for the device manager to function"
                      ), lambda: self.quit())

                manager = Manager()
                try:
                    manager.get_adapter(self.Config['last-adapter'])
                except DBusNoSuchAdapterError:
                    logging.error(
                        'Default adapter not found, trying first available.')
                    try:
                        manager.get_adapter(None)
                    except DBusNoSuchAdapterError:
                        logging.error('No adapter(s) found, exiting')
                        bmexit()

                self._applethandlerid = self.Applet.connect(
                    'g-signal', on_applet_signal)

                sw = self.builder.get_widget("scrollview", Gtk.ScrolledWindow)
                # Disable overlay scrolling
                if Gtk.get_minor_version() >= 16:
                    sw.props.overlay_scrolling = False

                self.List = ManagerDeviceList(
                    adapter=self.Config["last-adapter"], inst=self)

                self.List.show()
                sw.add(self.List)

                self.Toolbar = ManagerToolbar(self)
                self.Menu = ManagerMenu(self)
                self.Stats = ManagerStats(self)

                if self.List.is_valid_adapter():
                    self.List.populate_devices()

                self.List.connect("adapter-changed", self.on_adapter_changed)

                self.Config.bind_to_widget("show-toolbar", toolbar, "visible")
                self.Config.bind_to_widget("show-statusbar", statusbar,
                                           "visible")

            Manager.watch_name_owner(on_dbus_name_appeared,
                                     on_dbus_name_vanished)

        self.window.present_with_time(Gtk.get_current_event_time())

    def _on_configure(self, _window: Gtk.ApplicationWindow,
                      event: Gdk.EventConfigure) -> bool:
        width, height, x, y = self.Config["window-properties"]
        if event.x != x or event.y != y or event.width != width or event.height != height:
            self.Config["window-properties"] = [
                event.width, event.height, event.x, event.y
            ]
        return False

    def on_adapter_changed(self, lst: ManagerDeviceList, adapter: str) -> None:
        if adapter is not None:
            self.List.populate_devices()

    def inquiry(self) -> None:
        def prop_changed(_lst: ManagerDeviceList, _adapter: Adapter,
                         key_value: Tuple[str, Any]) -> None:
            key, value = key_value
            if key == "Discovering" and not value:
                prog.finalize()

                self.List.disconnect(s1)
                self.List.disconnect(s2)

        def on_progress(_lst: ManagerDeviceList, frac: float) -> None:
            if abs(1.0 - frac) <= 0.00001:
                if not prog.started():
                    prog.start()
            else:
                prog.fraction(frac)

        prog = ManagerProgressbar(self, text=_("Searching"))
        prog.connect("cancelled", lambda x: self.List.stop_discovery())

        def on_error(e: Exception) -> None:
            prog.finalize()
            MessageArea.show_message(*e_(e))

        self.List.discover_devices(error_handler=on_error)

        s1 = self.List.connect("discovery-progress", on_progress)
        s2 = self.List.connect("adapter-property-changed", prop_changed)

    @staticmethod
    def bond(device: Device) -> None:
        def error_handler(e: Exception) -> None:
            logging.exception(e)
            message = f"Pairing failed for:\n{device['Alias']} ({device['Address']})"
            Notification('Bluetooth', message, icon_name="blueman").show()

        device.pair(error_handler=error_handler)

    @staticmethod
    def adapter_properties() -> None:
        launch("blueman-adapters", name=_("Adapter Preferences"))

    @staticmethod
    def toggle_trust(device: Device) -> None:
        device['Trusted'] = not device['Trusted']

    @staticmethod
    def toggle_blocked(device: Device) -> None:
        device['Blocked'] = not device['Blocked']

    def send(self, device: Device) -> None:
        adapter = self.List.Adapter

        assert adapter

        command = f"blueman-sendto --source={adapter['Address']} --device={device['Address']}"
        launch(command, name=_("File Sender"))

    def remove(self, device: Device) -> None:
        assert self.List.Adapter
        self.List.Adapter.remove_device(device)
Exemplo n.º 21
0
 def _activate_status_icon(self) -> None:
     AppletService().Activate()
Exemplo n.º 22
0
 def renew() -> None:
     AppletService().DhcpClient('(s)', self.device.get_object_path())
Exemplo n.º 23
0
    def __init__(self):
        super().__init__(title=_("Bluetooth Devices"))

        self.Config = Config("org.blueman.general")

        self.Builder = Gtk.Builder()
        self.Builder.set_translation_domain("blueman")
        bind_textdomain_codeset("blueman", "UTF-8")
        self.Builder.add_from_file(UI_PATH + "/manager-main.ui")

        grid = self.Builder.get_object("grid")
        self.add(grid)
        self.set_name("BluemanManager")

        self.Plugins = PluginManager(ManagerPlugin, blueman.plugins.manager,
                                     self)
        self.Plugins.load_plugin()

        area = MessageArea()
        grid.attach(area, 0, 3, 1, 1)

        self._applethandlerid: Optional[int] = None

        # Add margin for resize grip or it will overlap
        if self.get_has_resize_grip():
            statusbar = self.Builder.get_object("statusbar")
            margin_right = statusbar.get_margin_right()
            statusbar.set_margin_right(margin_right + 10)

        def do_present(time):
            if self.props.visible:
                self.present_with_time(time)

        check_single_instance("blueman-manager", do_present)

        def on_window_delete(window, event):
            w, h = self.get_size()
            x, y = self.get_position()
            self.Config["window-properties"] = [w, h, x, y]
            Gtk.main_quit()

        setup_icon_path()

        try:
            self.Applet = AppletService()
        except DBusProxyFailed:
            print("Blueman applet needs to be running")
            exit()

        manager = Manager()
        try:
            manager.get_adapter(self.Config['last-adapter'])
        except DBusNoSuchAdapterError:
            logging.error('Default adapter not found, trying first available.')
            try:
                manager.get_adapter(None)
            except DBusNoSuchAdapterError:
                logging.error('No adapter(s) found')

        self.connect("delete-event", on_window_delete)
        self.props.icon_name = "blueman"

        w, h, x, y = self.Config["window-properties"]
        if w and h:
            self.resize(w, h)
        if x and y:
            self.move(x, y)

        sw = self.Builder.get_object("scrollview")
        # Disable overlay scrolling
        if Gtk.get_minor_version() >= 16:
            sw.props.overlay_scrolling = False

        self.List = ManagerDeviceList(adapter=self.Config["last-adapter"],
                                      inst=self)

        self.List.show()
        sw.add(self.List)

        self.Toolbar = ManagerToolbar(self)
        self.Menu = ManagerMenu(self)
        self.Stats = ManagerStats(self)

        if self.List.is_valid_adapter():
            self.List.display_known_devices(autoselect=True)

        self.List.connect("adapter-changed", self.on_adapter_changed)

        toolbar = self.Builder.get_object("toolbar")
        statusbar = self.Builder.get_object("statusbar")

        self.Config.bind_to_widget("show-toolbar", toolbar, "visible")
        self.Config.bind_to_widget("show-statusbar", statusbar, "visible")

        self.show()
Exemplo n.º 24
0
class ManagerDeviceMenu(Gtk.Menu):
    __ops__ = {}
    __instances__ = []

    def __init__(self, blueman):
        super(ManagerDeviceMenu, self).__init__()
        self.set_name("ManagerDeviceMenu")
        self.Blueman = blueman
        self.SelectedDevice = None

        self.is_popup = False

        self._device_property_changed_signal = self.Blueman.List.connect(
            "device-property-changed", self.on_device_property_changed)
        self._selection_done_signal = None

        ManagerDeviceMenu.__instances__.append(self)

        self._any_network = AnyNetwork()
        self._any_network.connect_signal('property-changed',
                                         self._on_service_property_changed)

        self._any_device = AnyDevice()
        self._any_device.connect_signal('property-changed',
                                        self._on_service_property_changed)

        try:
            self._appl = AppletService()
        except DBusProxyFailed:
            logging.error("** Failed to connect to applet", exc_info=True)
            self._appl = None

        self.generate()

    def __del__(self):
        logging.debug("deleting devicemenu")

    def popup(self, *args):
        self.is_popup = True

        if not self._device_property_changed_signal:
            self._device_property_changed_signal = self.Blueman.List.connect(
                "device-property-changed", self.on_device_property_changed)

        if not self._selection_done_signal:

            def disconnectall(x):
                self.disconnect(self._device_property_changed_signal)
                self.disconnect(self._selection_done_signal)

            self._selection_done_signal = self.connect("selection-done",
                                                       disconnectall)

        self.generate()

        super().popup(*args)

    def clear(self):
        def each(child, data):
            self.remove(child)
            child.destroy()

        self.foreach(each, None)

    def set_op(self, device, message):
        ManagerDeviceMenu.__ops__[device.get_object_path()] = message
        for inst in ManagerDeviceMenu.__instances__:
            logging.info("op: regenerating instance %s" % inst)
            if inst.SelectedDevice == self.SelectedDevice and not (
                    inst.is_popup and not inst.props.visible):
                inst.generate()

    def get_op(self, device):
        try:
            return ManagerDeviceMenu.__ops__[device.get_object_path()]
        except KeyError:
            return None

    def unset_op(self, device):
        del ManagerDeviceMenu.__ops__[device.get_object_path()]
        for inst in ManagerDeviceMenu.__instances__:
            logging.info("op: regenerating instance %s" % inst)
            if inst.SelectedDevice == self.SelectedDevice and not (
                    inst.is_popup and not inst.props.visible):
                inst.generate()

    def _on_service_property_changed(self, _service, key, _value, _path):
        if key == "Connected":
            self.generate()

    def on_connect(self, _item, service):
        device = service.device

        def success(obj, result, _user_data):
            logging.info("success")
            prog.message(_("Success!"))

            if isinstance(service, SerialPort
                          ) and SERIAL_PORT_SVCLASS_ID == service.short_uuid:
                MessageArea.show_message(
                    _("Serial port connected to %s") % result, None,
                    "dialog-information")
            else:
                MessageArea.close()

            self.unset_op(device)

        def fail(obj, result, _user_data):
            prog.message(_("Failed"))

            self.unset_op(device)
            logging.warning("fail %s" % result)
            msg, tb = e_(result.message)
            MessageArea.show_message(_("Connection Failed: ") + msg, tb)

        self.set_op(device, _("Connecting..."))
        prog = ManagerProgressbar(self.Blueman, False)

        if self._appl is None:
            fail(None, GLib.Error('Applet DBus Service not available'), None)
            return

        try:
            self._appl.SetTimeHint('(u)', Gtk.get_current_event_time())
        except Exception as e:
            logging.exception(e)

        self._appl.connect_service('(os)',
                                   device.get_object_path(),
                                   service.uuid,
                                   result_handler=success,
                                   error_handler=fail,
                                   timeout=GLib.MAXINT)

        prog.start()

    def on_disconnect(self, item, service, port=0):
        def ok(obj, result, user_date):
            logging.info("disconnect success")
            self.generate()

        def err(obj, result, user_date):
            logging.warning("disconnect failed %s" % result)
            msg, tb = e_(result.message)
            MessageArea.show_message(_("Disconnection Failed: ") + msg, tb)
            self.generate()

        if self._appl is None:
            err(None, GLib.Error('Applet DBus Service not available'), None)
            return

        self._appl.disconnect_service('(osd)',
                                      service.device.get_object_path(),
                                      service.uuid,
                                      port,
                                      result_handler=ok,
                                      error_handler=err)

    def on_device_property_changed(self, lst, device, tree_iter, key_value):
        key, value = key_value
        # print "menu:", key, value
        if lst.compare(tree_iter, lst.selected()):
            if key in ("Connected", "UUIDs", "Trusted", "Paired"):
                self.generate()

    def _generic_connect(self, item, device, connect):
        def fail(obj, result, user_date):
            logging.info("fail", result)
            prog.message(_("Failed"))
            self.unset_op(device)
            msg, tb = e_(result.message)
            MessageArea.show_message(_("Connection Failed: ") + msg)

        def success(obj, result, user_data):
            logging.info("success")
            prog.message(_("Success!"))
            MessageArea.close()
            self.unset_op(device)

        if connect:
            self.set_op(self.SelectedDevice, _("Connecting..."))
            self._appl.connect_service("(os)",
                                       device.get_object_path(),
                                       '00000000-0000-0000-0000-000000000000',
                                       result_handler=success,
                                       error_handler=fail,
                                       timeout=GLib.MAXINT)
        else:
            self.set_op(self.SelectedDevice, _("Disconnecting..."))
            self._appl.disconnect_service(
                "(osd)",
                device.get_object_path(),
                '00000000-0000-0000-0000-000000000000',
                0,
                result_handler=success,
                error_handler=fail,
                timeout=GLib.MAXINT)

        prog = ManagerProgressbar(self.Blueman, False)
        prog.start()

    def generate(self):
        self.clear()

        items = []

        if not self.is_popup or self.props.visible:
            selected = self.Blueman.List.selected()
            if not selected:
                return
            row = self.Blueman.List.get(selected, "alias", "paired",
                                        "connected", "trusted", "objpush",
                                        "device")
        else:
            (x, y) = self.Blueman.List.get_pointer()
            path = self.Blueman.List.get_path_at_pos(x, y)
            if path is not None:
                row = self.Blueman.List.get(path[0], "alias", "paired",
                                            "connected", "trusted", "objpush",
                                            "device")
            else:
                return

        self.SelectedDevice = row["device"]

        op = self.get_op(self.SelectedDevice)

        if op is not None:
            item = create_menuitem(op, "network-transmit-recieve")
            item.props.sensitive = False
            item.show()
            self.append(item)
            return

        # Generic (dis)connect
        # LE devices do not appear to expose certain properties like uuids until connect to at least once.
        # show generic connect for these as we will not show any way to connect otherwise.
        device_uuids = self.SelectedDevice['UUIDs']
        show_generic_connect = not device_uuids
        for uuid in device_uuids:
            service_uuid = ServiceUUID(uuid)
            if service_uuid.short_uuid in (AUDIO_SOURCE_SVCLASS_ID,
                                           AUDIO_SINK_SVCLASS_ID,
                                           HANDSFREE_AGW_SVCLASS_ID,
                                           HANDSFREE_SVCLASS_ID,
                                           HEADSET_SVCLASS_ID, HID_SVCLASS_ID,
                                           0x1812):
                show_generic_connect = True
                break
            elif not service_uuid.reserved:
                if uuid == '03b80e5a-ede8-4b33-a751-6ce34ec4c700':
                    show_generic_connect = True
                    break

        if not row["connected"] and show_generic_connect:
            connect_item = create_menuitem(_("_Connect"), "blueman")
            connect_item.connect("activate", self._generic_connect,
                                 self.SelectedDevice, True)
            connect_item.props.tooltip_text = _(
                "Connects auto connect profiles A2DP source, A2DP sink, and HID"
            )
            connect_item.show()
            self.append(connect_item)
        elif show_generic_connect:
            connect_item = create_menuitem(_("_Disconnect"), "network-offline")
            connect_item.props.tooltip_text = _(
                "Forcefully disconnect the device")
            connect_item.connect("activate", self._generic_connect,
                                 self.SelectedDevice, False)
            connect_item.show()
            self.append(connect_item)

        rets = self.Blueman.Plugins.run("on_request_menu_items", self,
                                        self.SelectedDevice)

        for ret in rets:
            if ret:
                for (item, pos) in ret:
                    items.append((pos, item))

        logging.debug(row["alias"])

        have_disconnectables = False
        have_connectables = False

        if True in map(lambda x: 100 <= x[0] < 200, items):
            have_disconnectables = True

        if True in map(lambda x: x[0] < 100, items):
            have_connectables = True

        if True in map(lambda x: x[0] >= 200,
                       items) and (have_connectables or have_disconnectables):
            item = Gtk.SeparatorMenuItem()
            item.show()
            items.append((199, item))

        if have_connectables:
            item = Gtk.MenuItem()
            label = Gtk.Label()
            label.set_markup(_("<b>Connect To:</b>"))
            label.props.xalign = 0.0

            label.show()
            item.add(label)
            item.props.sensitive = False
            item.show()
            items.append((0, item))

        if have_disconnectables:
            item = Gtk.MenuItem()
            label = Gtk.Label()
            label.set_markup(_("<b>Disconnect:</b>"))
            label.props.xalign = 0.0

            label.show()
            item.add(label)
            item.props.sensitive = False
            item.show()
            items.append((99, item))

        items.sort(key=itemgetter(0))
        for priority, item in items:
            self.append(item)

        if items:
            item = Gtk.SeparatorMenuItem()
            item.show()
            self.append(item)

        del items

        send_item = create_menuitem(_("Send a _File..."), "edit-copy")
        send_item.props.sensitive = False
        self.append(send_item)
        send_item.show()

        if row["objpush"]:
            send_item.connect("activate",
                              lambda x: self.Blueman.send(self.SelectedDevice))
            send_item.props.sensitive = True

        item = Gtk.SeparatorMenuItem()
        item.show()
        self.append(item)

        item = create_menuitem(_("_Pair"), "dialog-password")
        item.props.tooltip_text = _("Create pairing with the device")
        self.append(item)
        item.show()
        if not row["paired"]:
            item.connect("activate",
                         lambda x: self.Blueman.bond(self.SelectedDevice))
        else:
            item.props.sensitive = False

        if not row["trusted"]:
            item = create_menuitem(_("_Trust"), "blueman-trust")
            item.connect(
                "activate",
                lambda x: self.Blueman.toggle_trust(self.SelectedDevice))
            self.append(item)
            item.show()
        else:
            item = create_menuitem(_("_Untrust"), "blueman-untrust")
            self.append(item)
            item.connect(
                "activate",
                lambda x: self.Blueman.toggle_trust(self.SelectedDevice))
            item.show()
        item.props.tooltip_text = _("Mark/Unmark this device as trusted")

        item = create_menuitem(_("_Setup..."), "document-properties")
        self.append(item)
        item.connect("activate",
                     lambda x: self.Blueman.setup(self.SelectedDevice))
        item.show()
        item.props.tooltip_text = _("Run the setup assistant for this device")

        def on_rename(_item, device):
            def on_response(dialog, response_id):
                if response_id == Gtk.ResponseType.ACCEPT:
                    device.set('Alias', alias_entry.get_text())
                elif response_id == 1:
                    device.set('Alias', '')
                dialog.destroy()

            builder = Gtk.Builder()
            builder.set_translation_domain("blueman")
            bind_textdomain_codeset("blueman", "UTF-8")
            builder.add_from_file(UI_PATH + "/rename-device.ui")
            dialog = builder.get_object("dialog")
            dialog.set_transient_for(self.Blueman)
            dialog.props.icon_name = "blueman"
            alias_entry = builder.get_object("alias_entry")
            alias_entry.set_text(device['Alias'])
            dialog.connect("response", on_response)
            dialog.present()

        item = Gtk.MenuItem.new_with_mnemonic("R_ename device...")
        item.connect('activate', on_rename, self.SelectedDevice)
        self.append(item)
        item.show()

        item = Gtk.SeparatorMenuItem()
        item.show()
        self.append(item)

        item = create_menuitem(_("_Remove..."), "edit-delete")
        item.connect("activate",
                     lambda x: self.Blueman.remove(self.SelectedDevice))
        self.append(item)
        item.show()
        item.props.tooltip_text = _(
            "Remove this device from the known devices list")
Exemplo n.º 25
0
 def _activate_menu_item(self, *indexes):
     return AppletService().ActivateMenuItem('(ai)', indexes)
Exemplo n.º 26
0
 def _activate_status_icon(self):
     return AppletService().Activate()