class VpnSection(Section):
    def __init__(self):
        Section.__init__(self)

        #init
        self.vpn = Contain(app_theme.get_pixbuf("network/vpn.png"),
                           _("VPN Network"), lambda w: w)
        self.label = Label(_("Create a VPN connection"),
                           LABEL_COLOR,
                           underline=True,
                           enable_select=False,
                           enable_double_click=False)

        self.load(self.vpn, [self.label])
        self.no_auto_connect = False
        self.no_vpn_connecting = False
        self.this_setting = None
        self.vpn_path = None

    def init_state(self):
        vpn_active = nm_module.nmclient.get_vpn_active_connection()
        if vpn_active:
            self.vpn.set_active(True)
            for active in vpn_active:
                self.connect_vpn_signals(
                    nm_module.cache.get_spec_object(active.object_path))

        self.__init_signals()

    @classmethod
    def show_or_hide(self):
        return True

    def __init_signals(self):
        self.label.connect("button-release-event",
                           lambda w, p: self.jumpto_cb())
        Dispatcher.connect("vpn-redraw",
                           lambda w: self.vpn_redraw(None, None, None))
        Dispatcher.connect('vpn-start', self.vpn_start_cb)

        event_manager.add_callback("vpn-connecting", self.on_vpn_connecting)
        event_manager.add_callback('vpn-connected', self.vpn_connected)
        event_manager.add_callback('vpn-disconnected', self.vpn_disconnected)
        event_manager.add_callback('vpn-user-disconnect',
                                   self.on_user_stop_vpn)
        event_manager.add_callback('user-toggle-off-vpn-tray',
                                   self.user_toggle_off_vpn_tray)
        event_manager.add_callback('vpn-connection-removed', self.vpn_redraw)

    def user_toggle_off_vpn_tray(self, name, event, data):
        log.debug("toggle off vpn from tray")
        self.vpn.set_active(False)

    def on_user_stop_vpn(self, name, event, data):
        self.vpn.set_active(False)

    def vpn_redraw(self, name, event, data):
        if self.vpn.get_active():
            self.no_auto_connect = True
            self.vpn.set_active(True, emit=True)
            #self.toggle_on()
            self.show_all()

    def vpn_start_cb(self, widget, path):
        log.debug("vpn start by tray")
        vpn_active = nm_module.cache.get_spec_object(path)
        if vpn_active.get_vpnstate() < 5:
            self.vpn_path = path
            self.on_vpn_connecting(None, None, path)

    def connect_vpn_signals(self, active_vpn):
        active_vpn.connect("vpn-connected", self.vpn_connected)
        active_vpn.connect("vpn-disconnected", self.vpn_disconnected)
        active_vpn.connect('vpn-user-disconnect',
                           lambda w: self.vpn.set_active(False))

    def toggle_on(self):
        item_list = self.get_list()
        if item_list:
            item_list[-1].is_last = True
            self.tree.delete_all_items()
            self.tree.add_items(item_list)

    def on_active_conn_create(self, active_conn):
        net_manager.emit_vpn_start(active_conn)

    def try_active_vpn(self):
        from lists import VpnAutoMonitor
        monitor = VpnAutoMonitor()
        monitor.start()
        return monitor
        #for active_conn in nm_module.nmclient.get_anti_vpn_active_connection():
        #if len(nm_module.nmclient.get_vpn_active_connection()) == 0:
        #try:
        #active_conn.vpn_auto_connect(self.on_active_conn_create)
        #except:
        #pass
        #else:
        #break

    def toggle_on_after(self):
        if self.no_auto_connect:
            self.no_auto_connect = False
            pass
        else:
            if not self.vpn_path:
                self.monitor = self.try_active_vpn()
            else:
                self.on_vpn_connecting(None, None, self.vpn_path)

        vpn_active = nm_module.nmclient.get_vpn_active_connection()
        if vpn_active:
            # TODO fix for mutiple
            connection = vpn_active[0].get_connection()
            try:
                index = self.connection.index(connection)
                self.tree.visible_items[index].set_net_state(2)
                self.vpn_path = vpn_active[0].object_path
                return
            except Exception, e:
                log.error(e)
        else:
class WirelessSection(Section, WirelessDevice):
    def __init__(self):
        Section.__init__(self)
        WirelessDevice.__init__(self)
        self.wireless = Contain(app_theme.get_pixbuf("network/wifi.png"),
                                _("Wireless"), lambda w: w)
        self.label = Label(_("Set up a hidden wireless connection"),
                           LABEL_COLOR,
                           underline=True,
                           enable_select=False,
                           enable_double_click=False)

        space = gtk.VBox()
        space.set_size_request(-1, 15)

        self.load(self.wireless, [space, self.label])
        self.content_box.set_spacing(0)

        self.selected_item = None
        self.device_tree = None
        self.focused_device = None
        self.wireless_devices = None

    def add_switcher(self):
        if self.device_tree == None:
            self.device_tree = TreeView(
                [DeviceToggleItem(self.wireless_devices, 0)])
            self.device_tree.set_expand_column(1)
            self.content_box.pack_start(self.device_tree, False, True)
            self.content_box.reorder_child(self.device_tree, 0)
            net_manager.emit_wifi_switch(0)

    def remove_switcher(self):
        if self.device_tree\
           and self.device_tree in self.content_box.get_children():
            self.content_box.remove(self.device_tree)
            self.device_tree = None
            try:
                self.focused_device = self.wireless_devices[0]
            except:
                log.error("get no wireless devices but try to index")
                self.focused_device = None
            self.wireless_redraw(None)

    @classmethod
    def show_or_hide(self):
        if net_manager.device_manager.get_wireless_devices():
            self.wireless_devices = net_manager.device_manager.get_wireless_devices(
            )
            return True
        else:
            self.wireless_devices = []
            return False

    def init_state(self):
        self.ap_list = []
        self.wireless_devices = net_manager.device_manager.get_wireless_devices(
        )
        if self.wireless_devices:
            #self.device_dict = dict()
            self.focused_device = self.wireless_devices[0]
            if len(self.wireless_devices) > 1:
                self.add_switcher()
            self.tree.connect("single-click-item", self.set_selected_item)
            ## check state
            if self.get_state(self.wireless_devices):
                self.wireless.set_active(True)
        else:
            pass
        self.init_signals()

    def init_signals(self):
        self._init_signals()
        Dispatcher.connect("switch-device", self.switch_devices)
        Dispatcher.connect("wireless-device-add", self.device_added)
        Dispatcher.connect("ap-added", self.ap_added_callback)
        Dispatcher.connect("ap-removed", self.ap_removed_callback)
        Dispatcher.connect("wireless-redraw", self.wireless_redraw)
        self.label.connect("button-release-event",
                           self.create_a_hidden_network)
        event_manager.add_callback('hidden-connection-removed',
                                   self.on_delete_redraw)

    def switch_devices(self, widget, device):
        self.focused_device = device
        if self.device_tree:
            self.device_tree.visible_items[0].set_index(device)
        self.wireless_redraw(None)

    def on_delete_redraw(self, name, event, data):
        self.wireless_redraw(None)

    def wireless_redraw(self, widget):
        log.debug()
        if self.wireless.get_active():
            self.wireless.set_active(True, emit=True)
            self.show_all()

    def device_added(self, widget, device):
        self.wireless_devices = net_manager.device_manager.get_wireless_devices(
        )
        self._init_signals()
        if len(self.wireless_devices) > 1:
            self.add_switcher()
        else:
            self.remove_switcher()
        if self.wireless.get_active():
            self.wireless.set_active(True, emit=True)

    def create_a_hidden_network(self, widget, c):
        from wlan_config import HiddenSetting
        Dispatcher.to_setting_page(HiddenSetting(None), False)

    def ap_added_callback(self, widget):
        if self.wireless.get_active():
            self.wireless.set_active(True, emit=True)

    def ap_removed_callback(self, widget):
        if self.wireless.get_active():
            self.wireless.set_active(True, emit=True)

    def set_selected_item(self, widget, item, column, x, y):
        log.debug(item)
        self.selected_item = item

    def get_actives(self, ap_list):
        def to_item_state(device):
            if device.get_state() <= 30:
                return 0
            elif device.get_state() < 100:
                return 1
            elif device.get_state() == 100:
                return 2

        if not ap_list:
            return []
        index = []
        active_connection = self.focused_device.get_active_connection()
        if active_connection:
            try:
                ssid = active_connection.get_connection().get_setting(
                    "802-11-wireless").ssid
                index.append([[ap.get_ssid() for ap in ap_list].index(ssid),
                              to_item_state(self.focused_device)])
            except ValueError:
                print "not found in ap list"
        return index

    def _get_active_item(self):
        return filter(lambda i: i.get_net_state() > 0, self.tree.visible_items)

    def toggle_on_after(self):
        log.debug()
        indexs = self.get_actives(self.ap_list)
        if indexs:
            map(lambda (i, s): self.tree.visible_items[i].set_net_state(s),
                indexs)
        else:
            for d in self.wireless_devices:
                log.debug("try auto start")
                wifi = nm_module.cache.get_spec_object(d.object_path)
                wifi.auto_connect()

    def toggle_off(self):
        log.debug()
        self.ap_list = []
        self.selected_item = None
        for wireless_device in self.wireless_devices:
            wireless_device.nm_device_disconnect()

    def get_list(self):
        self.ap_list = list()
        if not self.wireless_devices:
            return []

        device_wifi = nm_module.cache.get_spec_object(
            self.focused_device.object_path)
        self.ap_list += device_wifi.order_ap_list()
        aps = map(lambda i: WirelessItem(i, self.focused_device), self.ap_list)
        hidden_list = self.get_hidden_connection()
        hiddens = map(lambda c: HidenItem(c), hidden_list)
        return aps + hiddens

    def __ap_list_merge(self):
        ap_ssid = set(map(lambda ap: ap.get_ssid(), self.ap_list))
        merged_ap = []
        for ap in self.ap_list:
            if ap.get_ssid() in ap_ssid:
                merged_ap.append(ap)
                ap_ssid.remove(ap.get_ssid())

        return merged_ap

    def get_hidden_connection(self):
        from shared_methods import net_manager
        return net_manager.get_hiddens()

        ## need to filter all aps
    def get_state(self, devices):
        for d in devices:
            if d.get_state() == 100:
                return True
        return False

    def device_stop(self, device):
        device.nm_device_disconnect()
class DSLSection(Section):
    def __init__(self):
        Section.__init__(self)
        self.dsl = Contain(app_theme.get_pixbuf("network/dsl.png"), _("DSL"),
                           lambda w: w)
        self.label = Label(_("Create a DSL connection"),
                           LABEL_COLOR,
                           underline=True,
                           enable_select=False,
                           enable_double_click=False)

        self.load(self.dsl, [self.label])

        self.active_connection = None

    def init_state(self):
        self.wired_devices = net_manager.device_manager.get_wired_devices()
        if self.wired_devices:
            self.__init_signals()
            if nm_module.nmclient.get_pppoe_active_connection():
                #print nm_module.nmclient.get_pppoe_active_connection()
                #print nm_module.nmclient.get_wired_active_connection()

                self.dsl.set_active(True)
        else:
            pass

    @classmethod
    def show_or_hide(self):
        if net_manager.device_manager.get_wired_devices():
            return True
        else:
            return False

    def __init_signals(self):
        self.label.connect("button-release-event",
                           lambda w, x: self.jumpto_setting())
        Dispatcher.connect("dsl-redraw",
                           lambda w: self.dsl_redraw(None, None, None))

        event_manager.add_callback('dsl-connection-start',
                                   self.connection_start_by_user)
        event_manager.add_callback('dsl-connection-removed', self.dsl_redraw)

        signal_list = [
            "device_active", "device_deactive", "device_unavailable",
            "activate_start", "activate_failed"
        ]

        for signal in signal_list:
            event_manager.add_callback(('dsl_%s' % signal).replace("_", "-"),
                                       getattr(self, signal))

    def connection_start_by_user(self, name, event, data):
        connection = data
        self.active_connection = connection

    def device_active(self, name, event, data):
        print "device active"
        if not self.dsl.get_active():
            self.dsl.set_active(True)
        if self.active_connection:
            index = self.connections.index(self.active_connection)
            if self.tree.visible_items != []:
                self.tree.visible_items[index].set_net_state(2)
                self.tree.queue_draw()

    def device_unavailable(self, name, event, data):
        print "device unavailable"

    def device_deactive(self, name, event, data):
        print "device deactive"
        new_state, old_state, reason = data
        if reason == 39:
            self.dsl.set_active(False)
            return
        if reason == 36:
            print "in fact there had device removed"
            ########################
            net_manager.init_devices()
            self.wired_devices = net_manager.wired_devices
            self._init_signals()
            self.tree.delete_all_items()
            item_list = self.get_list()
            if item_list:
                item_list[-1].is_last = True
                self.tree.add_items(item_list, 0, True)
                self.tree.set_size_request(-1,
                                           len(self.tree.visible_items) * 30)
        index = 0
        for d in self.wired_devices:
            if d.get_state() == 100:
                self.tree.visible_items[index].set_net_state(2)
            index += 1
        if not any([d.get_state() == 100 for d in net_manager.wired_devices]):
            self.dsl.set_active(False)

    def activate_start(self, name, event, data):
        print "active start in main"
        if self.active_connection:
            index = self.connections.index(self.active_connection)
            if self.tree.visible_items != []:
                self.tree.visible_items[index].set_net_state(1)
                self.tree.queue_draw()

    def activate_failed(self, name, event, data):
        print "device failded"

    def dsl_redraw(self, name, event, data):
        if self.dsl.get_active():
            log.debug("dsl redraw action")
            self.dsl.set_active(True, emit=True)

    def toggle_on(self):
        self.tree.delete_all_items()
        item_list = self.get_list()
        if item_list:
            item_list[-1].is_last = True
            self.tree.add_items(item_list)

    def toggle_on_after(self):
        active_dsl = nm_module.nmclient.get_pppoe_active_connection()
        if active_dsl:
            try:
                for a in active_dsl:
                    connection = a.get_connection()
                    index = self.connections.index(connection)
                    self.tree.visible_items[index].set_net_state(2)
            except:
                index = []
        else:
            # add auto connect stuff
            pass

    def toggle_off(self):
        active_dsl = nm_module.nmclient.get_pppoe_active_connection()
        if not active_dsl:
            return
        for wired_device in self.wired_devices:
            wired_device.nm_device_disconnect()

    def get_list(self):
        self.connections = nm_module.nm_remote_settings.get_pppoe_connections()
        log.debug(self.connections)
        return map(lambda c: DSLItem(c, None), self.connections)

    def jumpto_setting(self):
        Dispatcher.to_setting_page(DSLSetting(), hide_left=True)
        setting = nm_module.slider.get_page_by_name("setting")
        setting.create_new_connection()
class MobileSection(Section, MobileDevice):
    def __init__(self):
        Section.__init__(self)
        MobileDevice.__init__(self)
        # init values
        self.mobile = Contain(app_theme.get_pixbuf("network/3g.png"),
                              _("Mobile Network"), lambda w: w)
        self.label = Label(_("Mobile Configuration"),
                           LABEL_COLOR,
                           underline=True,
                           enable_select=False,
                           enable_double_click=False)

        self.load(self.mobile, [])
        #self.init_signal()

    def init_state(self):
        self.init_signal()
        pass

    def init_signal(self):
        self._init_signals()

    def get_item(self, device):
        modem_path = device.get_udi()
        try:
            index = self.devices.index(modem_path)
            return self.tree.visible_items[index]
        except:
            return None

    @classmethod
    def show_or_hide(self):
        return True

    def __init_signals(self):
        #nm_module.mmclient.connect("device-added", lambda w,p: mobile.set_active(True))
        Dispatcher.connect("mmdevice-added", self.device_added)
        self.label.connect("button-release-event",
                           lambda w, p: self.jumpto_cb())

    def device_added(self, widget, device):
        self.init_signal()
        if self.mobile.get_active():
            self.mobile.set_active(True)

    def toggle_on(self):
        item_list = self.get_list()
        if item_list:
            item_list[-1].is_last = True

            self.tree.delete_all_items()
            self.tree.add_items(item_list)

    def toggle_on_after(self):
        pass

    def toggle_off(self):
        pass

    def get_list(self):
        self.cdma = nm_module.mmclient.get_cdma_device()
        self.gsm = nm_module.mmclient.get_gsm_device()

        #self.cdma = nm_module.nm_remote_settings.get_cdma_connections()
        #self.gsm = nm_module.nm_remote_settings.get_gsm_connections()

        self.devices = self.cdma + self.gsm
        return map(lambda c: MobileItem(c, None), self.devices)

    def jumpto_cb(self):
        Dispatcher.to_setting_page(MobileSetting(), False)
class WiredSection(Section, WiredDevice):
    def __init__(self):
        Section.__init__(self)
        self.wire = Contain(app_theme.get_pixbuf("network/cable.png"),
                            _("Wired"), lambda w: w)
        self.load(self.wire, [])

    @classmethod
    def show_or_hide(self):
        if net_manager.device_manager.get_wired_devices():
            return True
        else:
            return False

    def init_state(self):
        self.wired_devices = net_manager.device_manager.get_wired_devices()
        if self.wired_devices:
            #if self.get_state(self.wired_devices):
            if nm_module.nmclient.get_wired_active_connection():
                self.wire.set_active(True)
        else:
            pass
        self.init_signals()

    def init_signals(self):
        Dispatcher.connect("wired-device-add", self.device_added)
        self._init_signals()

    def get_state(self, devices):
        return any([d.get_state() == 100 for d in devices])

    def device_added(self, widget, device):
        print "device added cb"
        self.wired_devices = net_manager.device_manager.get_wired_devices()
        self._init_signals()
        if self.wire.get_active():
            self.wire.set_active(True, emit=True)

    def get_list(self):
        return map(lambda d: WiredItem(d), self.wired_devices)

    def toggle_on(self):
        self.tree.delete_all_items()
        item_list = self.get_list()
        if item_list:
            item_list[-1].is_last = True
            self.tree.add_items(item_list, 0, True)
            self.tree.set_size_request(-1, len(self.tree.visible_items) * 30)

    def toggle_on_after(self):
        for i, d in enumerate(self.wired_devices):
            if d.get_state() == 100:
                self.tree.visible_items[i].set_net_state(2)
            elif len(self.wired_devices) == 1:
                device_ethernet = nm_module.cache.get_spec_object(
                    d.object_path)
                if device_ethernet:
                    device_ethernet.auto_connect()

    def toggle_off(self):
        log.debug()
        for wired_device in self.wired_devices:
            wired_device.nm_device_disconnect()
class VpnSection(Section):
    def __init__(self):
        Section.__init__(self)

        #init
        self.vpn = Contain(app_theme.get_pixbuf("network/vpn.png"), _("VPN Network"), lambda w:w)
        self.label = Label(_("Create a VPN connection"), 
                           LABEL_COLOR,
                           underline=True,
                           enable_select=False,
                           enable_double_click=False)

        self.load(self.vpn, [self.label])
        self.no_auto_connect = False
        self.no_vpn_connecting = False
        self.this_setting = None
        self.vpn_path = None

    def init_state(self):
        vpn_active = nm_module.nmclient.get_vpn_active_connection()
        if vpn_active:
            self.vpn.set_active(True)
            for active in vpn_active:
                self.connect_vpn_signals(nm_module.cache.get_spec_object(active.object_path))
            
        self.__init_signals()

    @classmethod
    def show_or_hide(self):
        return True

    def __init_signals(self):
        self.label.connect("button-release-event", lambda w,p: self.jumpto_cb())
        Dispatcher.connect("vpn-redraw", lambda w: self.vpn_redraw(None, None, None))
        Dispatcher.connect('vpn-start', self.vpn_start_cb)

        event_manager.add_callback("vpn-connecting", self.on_vpn_connecting)
        event_manager.add_callback('vpn-connected', self.vpn_connected)
        event_manager.add_callback('vpn-disconnected', self.vpn_disconnected)
        event_manager.add_callback('vpn-user-disconnect', self.on_user_stop_vpn)
        event_manager.add_callback('user-toggle-off-vpn-tray', self.user_toggle_off_vpn_tray)
        event_manager.add_callback('vpn-connection-removed', self.vpn_redraw)

    def user_toggle_off_vpn_tray(self, name, event, data):
        log.debug("toggle off vpn from tray")
        self.vpn.set_active(False)

    def on_user_stop_vpn(self, name, event, data):
        self.vpn.set_active(False)

    def vpn_redraw(self, name, event, data):
        if self.vpn.get_active():
            self.no_auto_connect = True
            self.vpn.set_active(True, emit=True)
            #self.toggle_on()
            self.show_all()

    def vpn_start_cb(self, widget, path):
        log.debug("vpn start by tray")
        vpn_active = nm_module.cache.get_spec_object(path)
        if vpn_active.get_vpnstate() < 5:
            self.vpn_path = path
            self.on_vpn_connecting(None, None, path)


    def connect_vpn_signals(self, active_vpn):
        active_vpn.connect("vpn-connected", self.vpn_connected)
        active_vpn.connect("vpn-disconnected", self.vpn_disconnected)
        active_vpn.connect('vpn-user-disconnect', lambda w: self.vpn.set_active(False))

    def toggle_on(self):
        item_list = self.get_list()
        if item_list:
            item_list[-1].is_last = True
            self.tree.delete_all_items()
            self.tree.add_items(item_list)

    def on_active_conn_create(self, active_conn):
        net_manager.emit_vpn_start(active_conn)

    def try_active_vpn(self):
        from lists import VpnAutoMonitor
        monitor = VpnAutoMonitor()
        monitor.start()
        return monitor
        #for active_conn in nm_module.nmclient.get_anti_vpn_active_connection():
            #if len(nm_module.nmclient.get_vpn_active_connection()) == 0:
                #try:
                    #active_conn.vpn_auto_connect(self.on_active_conn_create)
                #except:
                    #pass
            #else:
                #break

    def toggle_on_after(self):
        if self.no_auto_connect:
            self.no_auto_connect = False
            pass
        else:
            if not self.vpn_path:
                self.monitor = self.try_active_vpn()
            else:
                self.on_vpn_connecting(None, None, self.vpn_path)

        vpn_active = nm_module.nmclient.get_vpn_active_connection()
        if vpn_active:
            # TODO fix for mutiple
            connection = vpn_active[0].get_connection()
            try:
                index = self.connection.index(connection)
                self.tree.visible_items[index].set_net_state(2)
                self.vpn_path = vpn_active[0].object_path
                return
            except Exception, e:
                log.error(e)
        else:
class DSLSection(Section):
    def __init__(self):
        Section.__init__(self)
        self.dsl = Contain(app_theme.get_pixbuf("network/dsl.png"), _("DSL"), lambda w: w)
        self.label =  Label(_("Create a DSL connection"), 
                          LABEL_COLOR,
                          underline=True,
                          enable_select=False,
                          enable_double_click=False)
        
        self.load(self.dsl, [self.label])

        self.active_connection = None

    def init_state(self):
        self.wired_devices = net_manager.device_manager.get_wired_devices()
        if self.wired_devices:
            self.__init_signals()
            if nm_module.nmclient.get_pppoe_active_connection():
                #print nm_module.nmclient.get_pppoe_active_connection()
                #print nm_module.nmclient.get_wired_active_connection()

                self.dsl.set_active(True)
        else:
            pass

    @classmethod
    def show_or_hide(self):
        if net_manager.device_manager.get_wired_devices():
            return True
        else:
            return False

    def __init_signals(self):
        self.label.connect("button-release-event", lambda w,x: self.jumpto_setting())
        Dispatcher.connect("dsl-redraw", lambda w: self.dsl_redraw(None, None,None))

        event_manager.add_callback('dsl-connection-start', self.connection_start_by_user)
        event_manager.add_callback('dsl-connection-removed', self.dsl_redraw)


        signal_list = ["device_active",
                              "device_deactive",
                              "device_unavailable",
                              "activate_start",
                              "activate_failed"]

        for signal in signal_list:
            event_manager.add_callback(('dsl_%s'%signal).replace("_", "-"), getattr(self, signal))


    def connection_start_by_user(self, name, event, data):
        connection = data
        self.active_connection = connection

    def device_active(self, name, event, data):
        print "device active"
        if not self.dsl.get_active():
            self.dsl.set_active(True)
        if self.active_connection:
            index = self.connections.index(self.active_connection)
            if self.tree.visible_items != []:
                self.tree.visible_items[index].set_net_state(2)
                self.tree.queue_draw()

    def device_unavailable(self, name, event, data):
        print "device unavailable"

    def device_deactive(self, name, event, data):
        print "device deactive"
        new_state, old_state, reason = data
        if reason == 39:
            self.dsl.set_active(False)
            return
        if reason == 36:
            print "in fact there had device removed"
        ########################
            net_manager.init_devices()
            self.wired_devices = net_manager.wired_devices
            self._init_signals()
            self.tree.delete_all_items()
            item_list = self.get_list()
            if item_list:
                item_list[-1].is_last = True
                self.tree.add_items(item_list, 0, True)
                self.tree.set_size_request(-1, len(self.tree.visible_items)*30)
        index = 0
        for d in self.wired_devices:
            if d.get_state() == 100:
                self.tree.visible_items[index].set_net_state(2)
            index += 1
        if not any([d.get_state() == 100 for d in net_manager.wired_devices]):
            self.dsl.set_active(False)

    def activate_start(self, name, event, data):
        print "active start in main"
        if self.active_connection:
            index = self.connections.index(self.active_connection)
            if self.tree.visible_items != []:
                self.tree.visible_items[index].set_net_state(1)
                self.tree.queue_draw()

    def activate_failed(self, name, event, data):
        print "device failded"

    def dsl_redraw(self, name, event, data):
        if self.dsl.get_active():
            log.debug("dsl redraw action")
            self.dsl.set_active(True, emit=True)

    def toggle_on(self):
        self.tree.delete_all_items()
        item_list = self.get_list()
        if item_list:
            item_list[-1].is_last = True
            self.tree.add_items(item_list)

    def toggle_on_after(self):
        active_dsl = nm_module.nmclient.get_pppoe_active_connection()
        if active_dsl:
            try:
                for a in active_dsl:
                    connection = a.get_connection()
                    index = self.connections.index(connection)
                    self.tree.visible_items[index].set_net_state(2)
            except:
                index = []
        else:
            # add auto connect stuff
            pass
            
    def toggle_off(self):
        active_dsl = nm_module.nmclient.get_pppoe_active_connection()
        if not active_dsl:
            return
        for wired_device in self.wired_devices:
            wired_device.nm_device_disconnect()

    def get_list(self):
        self.connections =  nm_module.nm_remote_settings.get_pppoe_connections()
        log.debug(self.connections)
        return map(lambda c: DSLItem(c, None), self.connections)

    def jumpto_setting(self):
        Dispatcher.to_setting_page(DSLSetting(),hide_left=True)
        setting = nm_module.slider.get_page_by_name("setting")
        setting.create_new_connection()
class WirelessSection(Section, WirelessDevice):

    def __init__(self):
        Section.__init__(self)
        WirelessDevice.__init__(self)
        self.wireless = Contain(app_theme.get_pixbuf("network/wifi.png"), _("Wireless"), lambda w:w)
        self.label =  Label(_("Set up a hidden wireless connection"), 
                          LABEL_COLOR,
                          underline=True,
                          enable_select=False,
                          enable_double_click=False)

        space = gtk.VBox()
        space.set_size_request(-1, 15)

        self.load(self.wireless, [space, self.label])
        self.content_box.set_spacing(0)

        self.selected_item = None
        self.device_tree = None
        self.focused_device = None
        self.wireless_devices = None

    def add_switcher(self):
        if self.device_tree == None:
            self.device_tree = TreeView([DeviceToggleItem(self.wireless_devices, 0)])
            self.device_tree.set_expand_column(1)
            self.content_box.pack_start(self.device_tree, False, True)
            self.content_box.reorder_child(self.device_tree, 0)
            net_manager.emit_wifi_switch(0)

    def remove_switcher(self):
        if self.device_tree\
           and self.device_tree in self.content_box.get_children():
            self.content_box.remove(self.device_tree)
            self.device_tree = None
            try:
                self.focused_device = self.wireless_devices[0]
            except:
                log.error("get no wireless devices but try to index")
                self.focused_device = None
            self.wireless_redraw(None)


    @classmethod
    def show_or_hide(self):
        if net_manager.device_manager.get_wireless_devices():
            self.wireless_devices = net_manager.device_manager.get_wireless_devices()
            return True
        else:
            self.wireless_devices = []
            return False

    def init_state(self):
        self.ap_list = []
        self.wireless_devices = net_manager.device_manager.get_wireless_devices()
        if self.wireless_devices:
            #self.device_dict = dict()
            self.focused_device = self.wireless_devices[0]
            if len(self.wireless_devices) > 1:
                self.add_switcher()
            self.tree.connect("single-click-item", self.set_selected_item)
            ## check state
            if self.get_state(self.wireless_devices):
                self.wireless.set_active(True)
        else:
            pass
        self.init_signals()


    def init_signals(self):
        self._init_signals() 
        Dispatcher.connect("switch-device", self.switch_devices)
        Dispatcher.connect("wireless-device-add", self.device_added)
        Dispatcher.connect("ap-added", self.ap_added_callback)
        Dispatcher.connect("ap-removed", self.ap_removed_callback)
        Dispatcher.connect("wireless-redraw", self.wireless_redraw)
        self.label.connect("button-release-event", self.create_a_hidden_network)
        event_manager.add_callback('hidden-connection-removed', self.on_delete_redraw)

    def switch_devices(self, widget, device):
        self.focused_device = device
        if self.device_tree:
            self.device_tree.visible_items[0].set_index(device)
        self.wireless_redraw(None)

    def on_delete_redraw(self, name, event, data):
        self.wireless_redraw(None)

    def wireless_redraw(self, widget):
        log.debug()
        if self.wireless.get_active():
            self.wireless.set_active(True, emit=True)
            self.show_all()


    def device_added(self, widget, device):
        self.wireless_devices = net_manager.device_manager.get_wireless_devices()
        self._init_signals()
        if len(self.wireless_devices) > 1:
            self.add_switcher()
        else:
            self.remove_switcher()
        if self.wireless.get_active():
            self.wireless.set_active(True, emit=True)

    def create_a_hidden_network(self, widget, c):
        from wlan_config import HiddenSetting
        Dispatcher.to_setting_page(HiddenSetting(None), False)

    def ap_added_callback(self, widget):
        if self.wireless.get_active():
            self.wireless.set_active(True, emit=True)

    def ap_removed_callback(self, widget):
        if self.wireless.get_active():
            self.wireless.set_active(True, emit=True)

    def set_selected_item(self, widget, item, column, x, y):
        log.debug(item)
        self.selected_item = item

    def get_actives(self, ap_list):
        def to_item_state(device):
            if device.get_state() <= 30:
                return 0
            elif device.get_state() < 100:
                return 1
            elif device.get_state() == 100:
                return 2

        if not ap_list:
            return []
        index = []
        active_connection = self.focused_device.get_active_connection()
        if active_connection:
            try:
                ssid = active_connection.get_connection().get_setting("802-11-wireless").ssid
                index.append([[ap.get_ssid() for ap in ap_list].index(ssid), to_item_state(self.focused_device)])
            except ValueError:
                print "not found in ap list"
        return index
    

    def _get_active_item(self):
        return filter(lambda i: i.get_net_state() > 0, self.tree.visible_items)

    def toggle_on_after(self):
        log.debug()
        indexs = self.get_actives(self.ap_list)
        if indexs:
            map(lambda (i, s): self.tree.visible_items[i].set_net_state(s), indexs)
        else:
            for d in self.wireless_devices:
                log.debug("try auto start")
                wifi = nm_module.cache.get_spec_object(d.object_path)
                wifi.auto_connect()

    def toggle_off(self):
        log.debug()
        self.ap_list = []
        self.selected_item = None
        for wireless_device in self.wireless_devices:
            wireless_device.nm_device_disconnect()

    def get_list(self):
        self.ap_list = list()
        if not self.wireless_devices:
            return []

        device_wifi = nm_module.cache.get_spec_object(self.focused_device.object_path)
        self.ap_list += device_wifi.order_ap_list()
        aps = map(lambda i:WirelessItem(i, self.focused_device), self.ap_list)
        hidden_list = self.get_hidden_connection()
        hiddens = map(lambda c: HidenItem(c), hidden_list)
        return aps + hiddens

    def __ap_list_merge(self):
        ap_ssid = set(map(lambda ap: ap.get_ssid(), self.ap_list))
        merged_ap = []
        for ap in self.ap_list:
            if ap.get_ssid() in ap_ssid:
                merged_ap.append(ap)
                ap_ssid.remove(ap.get_ssid())

        return merged_ap

    def get_hidden_connection(self):
        from shared_methods import net_manager
        return net_manager.get_hiddens()

        ## need to filter all aps
    def get_state(self, devices):
        for d in devices:
            if d.get_state() == 100:
                return True
        return False
    
    def device_stop(self, device):
        device.nm_device_disconnect()
class WiredSection(Section, WiredDevice):

    def __init__(self):
        Section.__init__(self)
        self.wire = Contain(app_theme.get_pixbuf("network/cable.png"), _("Wired"), lambda w:w)
        self.load(self.wire, [])
    
    @classmethod
    def show_or_hide(self):
        if net_manager.device_manager.get_wired_devices():
            return True
        else:
            return False

    def init_state(self):
        self.wired_devices = net_manager.device_manager.get_wired_devices()
        if self.wired_devices:
            #if self.get_state(self.wired_devices):
            if nm_module.nmclient.get_wired_active_connection():
                self.wire.set_active(True)
        else:
            pass
        self.init_signals()

    def init_signals(self):
        Dispatcher.connect("wired-device-add", self.device_added)
        self._init_signals()
    
    def get_state(self, devices):
        return any([d.get_state() == 100 for d in devices])
    
    def device_added(self, widget, device):
        print "device added cb"
        self.wired_devices = net_manager.device_manager.get_wired_devices()
        self._init_signals()
        if self.wire.get_active():
            self.wire.set_active(True, emit=True)

    def get_list(self):
        return map(lambda d: WiredItem(d), self.wired_devices)

    def toggle_on(self):
        self.tree.delete_all_items()
        item_list = self.get_list()
        if item_list:
            item_list[-1].is_last = True
            self.tree.add_items(item_list, 0, True)
            self.tree.set_size_request(-1, len(self.tree.visible_items)*30)

    def toggle_on_after(self):
        for i,d in enumerate(self.wired_devices):
            if d.get_state() == 100:
                self.tree.visible_items[i].set_net_state(2)
            elif len(self.wired_devices) == 1:
                device_ethernet = nm_module.cache.get_spec_object(d.object_path)
                if device_ethernet:
                    device_ethernet.auto_connect()

    def toggle_off(self):
        log.debug()
        for wired_device in self.wired_devices:
            wired_device.nm_device_disconnect()
Пример #10
0
class MobileSection(Section, MobileDevice):

    def __init__(self):
        Section.__init__(self)
        MobileDevice.__init__(self)
        # init values
        self.mobile = Contain(app_theme.get_pixbuf("network/3g.png"), _("Mobile Network"), lambda w:w)
        self.label = Label(_("Mobile Configuration"),
                      LABEL_COLOR,
                      underline=True,
                      enable_select=False,
                      enable_double_click=False)

        self.load(self.mobile, [])
        #self.init_signal()

    def init_state(self):
        self.init_signal()
        pass

    def init_signal(self):
        self._init_signals()

    def get_item(self, device):
        modem_path =device.get_udi()
        try:
            index = self.devices.index(modem_path)
            return self.tree.visible_items[index]
        except:
            return None

    @classmethod
    def show_or_hide(self):
        return True

    def __init_signals(self):
        #nm_module.mmclient.connect("device-added", lambda w,p: mobile.set_active(True))
        Dispatcher.connect("mmdevice-added", self.device_added)
        self.label.connect("button-release-event", lambda w,p: self.jumpto_cb())

    def device_added(self, widget, device):
        self.init_signal()
        if self.mobile.get_active():
            self.mobile.set_active(True)

    def toggle_on(self):
        item_list = self.get_list()
        if item_list:
            item_list[-1].is_last = True

            self.tree.delete_all_items()
            self.tree.add_items(item_list)

    def toggle_on_after(self):
        pass

    def toggle_off(self):
        pass

    def get_list(self):
        self.cdma = nm_module.mmclient.get_cdma_device()
        self.gsm = nm_module.mmclient.get_gsm_device()

        #self.cdma = nm_module.nm_remote_settings.get_cdma_connections()
        #self.gsm = nm_module.nm_remote_settings.get_gsm_connections()
        
        self.devices = self.cdma + self.gsm
        return map(lambda c: MobileItem(c, None), self.devices)
    
    def jumpto_cb(self):
        Dispatcher.to_setting_page(MobileSetting(), False)