Exemplo n.º 1
0
class SMTPSetup(HIGWindow):
    """
    SMTP editor.
    """
    
    def __init__(self):
        HIGWindow.__init__(self)
        
        self.wtitle = _("SMTP Account Editor")

        # header
        self.title_markup = "<span size='16500' weight='heavy'>%s</span>"
        self.ttitle = HIGEntryLabel("")
        self.ttitle.set_line_wrap(False)
        self.ttitle.set_markup(self.title_markup % self.wtitle)
        self.umit_logo = gtk.Image()
        self.umit_logo.set_from_file(logo)
        # schemas name
        self.schema_name_lbl = HIGEntryLabel(_("Schema name"))
        self.schema_name = gtk.combo_box_entry_new_text()
        self.schema_name.connect('changed', self._check_schema)
        # smtp server
        self.smtp_server_lbl = HIGEntryLabel(_("Server"))
        self.smtp_server = gtk.Entry()
        self.smtp_port_lbl = HIGEntryLabel(_("Port"))
        self.smtp_port = gtk.Entry()
        # sending mail..
        self.smtp_mailfrom_lbl = HIGEntryLabel(_("Mail from"))
        self.smtp_mailfrom = gtk.Entry()
        # smtp auth
        self.smtp_need_auth = gtk.CheckButton(_("Servers requires authentication"))
        self.smtp_need_auth.connect('toggled', self._auth_need)
        self.smtp_login_lbl = HIGEntryLabel(_("Username"))
        self.smtp_login = gtk.Entry()
        self.smtp_passwd_lbl = HIGEntryLabel(_("Password"))
        self.smtp_passwd = gtk.Entry()
        self.smtp_passwd.set_visibility(False)
        self._auth_need(None)
        # smtp encryption
        self.smtp_encrypt_tls = gtk.CheckButton(_("Use TLS Encryption"))

        """
        Missing: SSL encryption,
                 Other authentication methods.
        """ 

        # bottom buttons
        self.help = HIGButton(stock=gtk.STOCK_HELP)
        self.help.connect('clicked', self._show_help)
        self.apply = HIGButton(stock=gtk.STOCK_APPLY)
        self.apply.connect('clicked', self._save_schema)
        self.cancel = HIGButton(stock=gtk.STOCK_CANCEL)
        self.cancel.connect('clicked', self._exit)
        self.ok = HIGButton(stock=gtk.STOCK_OK)
        self.ok.connect('clicked', self._save_schema_and_leave)
        
        self.load_schemas()
        
        self.__set_props()
        self.__do_layout()

        self.connect('destroy', self._exit)
        

    def load_schemas(self):
        """
        Load schemas profiles.
        """
        schemas = ConfigParser()
        schemas.read(Path.smtp_schemas)
        
        self.sections = [ ]
        self.schema_name.get_model().clear()
        for section in schemas.sections():
            self.sections.append(section)
            self.schema_name.append_text(section)
            
        self.schema_name.set_active(0)
        self._check_schema(None)

    
    def _load_schema(self):
        """
        Load current set schedule schema.
        """
        schema = ConfigParser()
        schema.read(Path.smtp_schemas)
        
        enable = {'tls':self.smtp_encrypt_tls.set_active,
                  'auth':self.smtp_need_auth.set_active}
        values = {'user':self.smtp_login.set_text,
                  'pass':self.smtp_passwd.set_text,
                  'server':self.smtp_server.set_text,
                  'port':self.smtp_port.set_text,
                  'mailfrom':self.smtp_mailfrom.set_text}
        
        for item in schema.items(self.schema_name.get_active_text()):
            if item[0] in ('tls', 'auth'):
                enable[item[0]](int(item[1]))
            else:
                values[item[0]](item[1])
                

    def _check_schema(self, event):
        """
        Check if current text in schema_name combobox is a schema name.
        """
        if self.schema_name.get_active_text() in self.sections: 
            # load schema
            self._load_schema()
        else:
            # reset to default values
            self.smtp_mailfrom.set_text('')
            self.smtp_server.set_text('')
            self.smtp_port.set_text('')
            self.smtp_encrypt_tls.set_active(False)
            self.smtp_login.set_text('')
            self.smtp_passwd.set_text('')
            self.smtp_need_auth.set_active(False)
            self._auth_need(None)
            
    
    def _auth_need(self, event):
        """
        SMTP Authentication toggled.
        """
        status = self.smtp_need_auth.get_active()
        self.smtp_login.set_sensitive(status)
        self.smtp_passwd.set_sensitive(status)
        self.smtp_login_lbl.set_sensitive(status)
        self.smtp_passwd_lbl.set_sensitive(status)
    
    
    def _save_schema(self, event):
        """
        Save current schema.
        """
        schema = self.schema_name.get_active_text()
        server = self.smtp_server.get_text()
        port = self.smtp_port.get_text()
        auth = self.smtp_need_auth.get_active()
        mailfrom = self.smtp_mailfrom.get_text()
        
        if auth:
            user = self.smtp_login.get_text()
            passwd = self.smtp_passwd.get_text()
        
        if auth and not (user and passwd):
            dlg = HIGAlertDialog(self, 
                                 message_format=_('SMTP Schema - Error\
 while saving.'),
                                 secondary_text=_("You need to specify an \
username and password for this SMTP Schema."))
            
            dlg.run()
            dlg.destroy()
            return
        
        if not schema or not server or not port or not mailfrom:
            dlg = HIGAlertDialog(self, 
                                 message_format=_('SMTP Schema - Error\
 while saving.'),
                                 secondary_text=_("The following fields \
need to be filled: Schema Name, Server, Port and Mail from."))
            
            dlg.run()
            dlg.destroy()
            return
        
        # write schema to file
        s_cfg = ConfigParser()
        s_cfg.read(Path.smtp_schemas)
        
        if not s_cfg.has_section(schema):
            new_sec = True
            s_cfg.add_section(schema)
        else:
            new_sec = False
        
        if auth:
            s_cfg.set(schema, 'auth', '1')
        else:
            s_cfg.set(schema, 'auth', '0')
            user = ''
            passwd = ''
            
        s_cfg.set(schema, 'port', port)
        s_cfg.set(schema, 'server', server)
        s_cfg.set(schema, 'user', user)
        s_cfg.set(schema, 'pass', passwd)
        s_cfg.set(schema, 'mailfrom', mailfrom)
        
        if self.smtp_encrypt_tls.get_active():
            s_cfg.set(schema, 'tls', '1')
        else:
            s_cfg.set(schema, 'tls', '0')
            
        s_cfg.write(open(Path.smtp_schemas, 'w'))
        
        if new_sec:
            self.load_schemas()
        
        
    def _save_schema_and_leave(self, event):
        """
        Save current schema and close editor.
        """
        self._save_schema(None)
        self._exit(None)
        
        
    def __set_props(self):
        """
        Set window properties.
        """
        self.set_title(self.wtitle)
       
    
    def _show_help(self, event):
        """
        Open SMTP Setup help
        """
        show_help(self, "smtpsetup.html")


    def __do_layout(self):
        """
        Layout widgets in window.
        """
        main_vbox = HIGVBox()
        main_vbox.set_border_width(5)
        main_vbox.set_spacing(12)
        header_hbox = HIGHBox()
        schema_table = HIGTable()
        auth_table = HIGTable()
        btns_hbox = HIGHBox()

        header_hbox._pack_expand_fill(self.ttitle)
        header_hbox._pack_noexpand_nofill(self.umit_logo)
        
        # schema name
        schema_table.attach_label(self.schema_name_lbl, 0, 1, 0, 1)
        schema_table.attach_entry(self.schema_name, 1, 2, 0, 1)
        
        # smtp server
        schema_table.attach_label(self.smtp_server_lbl, 0, 1, 1, 2)
        schema_table.attach_entry(self.smtp_server, 1, 2, 1, 2)

        # smtp server port
        schema_table.attach_label(self.smtp_port_lbl, 0, 1, 2, 3)
        schema_table.attach_entry(self.smtp_port, 1, 2, 2, 3)
        
        # smtp mail from
        schema_table.attach_label(self.smtp_mailfrom_lbl, 0, 1, 3, 4)
        schema_table.attach_entry(self.smtp_mailfrom, 1, 2, 3, 4)
        
        # smtp user
        auth_table.attach_label(self.smtp_login_lbl, 0, 1, 0, 1)
        auth_table.attach_entry(self.smtp_login, 1, 2, 0, 1)
        
        # smtp passwd
        auth_table.attach_label(self.smtp_passwd_lbl, 0, 1, 1, 2)
        auth_table.attach_label(self.smtp_passwd, 1, 2, 1, 2)
        
        # bottom buttons
        btns_hbox.set_homogeneous(True)
        btns_hbox._pack_expand_fill(self.help)
        btns_hbox._pack_expand_fill(hig_box_space_holder())
        btns_hbox._pack_expand_fill(self.apply)
        btns_hbox._pack_expand_fill(self.cancel)
        btns_hbox._pack_expand_fill(self.ok)
                
        main_vbox._pack_noexpand_nofill(header_hbox)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(schema_table)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(self.smtp_need_auth)
        main_vbox._pack_noexpand_nofill(auth_table)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(self.smtp_encrypt_tls)
        main_vbox.pack_end(btns_hbox, False, False, 0)
        
        self.add(main_vbox)


    def _exit(self, event):
        """
        Close current window.
        """
        self.destroy()
Exemplo n.º 2
0
class SchedProfileEditor(HIGWindow):
    """
    Scheduling Profiles Editor
    """

    def __init__(self, daddy, profile=None):
        HIGWindow.__init__(self)
        self.daddy = daddy

        self.wtitle = _("Scheduling Profiles Editor")
        self.start_profile = profile

        # header
        self.title_markup = "<span size='16500' weight='heavy'>%s</span>"
        self.ttitle = HIGEntryLabel("")
        self.ttitle.set_line_wrap(False)
        self.ttitle.set_markup(self.title_markup % self.wtitle)
        self.umit_logo = gtk.Image()
        self.umit_logo.set_from_file(logo)
        # profiles name
        self.schedp_name_lbl = HIGEntryLabel(_("Scheduling Profile"))
        self.schedp_name = gtk.combo_box_entry_new_text()
        self.schedp_name.connect("changed", self._check_profile)
        # cron format
        self.cron_frame = HIGFrame(_("Schedule"))
        self.cron_minute_lbl = HIGEntryLabel(_("Minute"))
        self.cron_minute = gtk.Entry()
        self.cron_hour_lbl = HIGEntryLabel(_("Hour"))
        self.cron_hour = gtk.Entry()
        self.cron_day_lbl = HIGEntryLabel(_("Day of month"))
        self.cron_day = gtk.Entry()
        self.cron_month_lbl = HIGEntryLabel(_("Month"))
        self.cron_month = gtk.Entry()
        self.cron_weekday_lbl = HIGEntryLabel(_("Weekday"))
        self.cron_weekday = gtk.Entry()
        # bottom buttons
        self.help = HIGButton(stock=gtk.STOCK_HELP)
        self.help.connect("clicked", self._show_help)
        self.apply = HIGButton(stock=gtk.STOCK_APPLY)
        self.apply.connect("clicked", self._save_profile)
        self.cancel = HIGButton(stock=gtk.STOCK_CANCEL)
        self.cancel.connect("clicked", self._exit)
        self.ok = HIGButton(stock=gtk.STOCK_OK)
        self.ok.connect("clicked", self._save_profile_and_leave)

        self.load_profiles()
        self.__set_props()
        self.__do_layout()

        self.connect("destroy", self._exit)

    def load_profiles(self):
        """
        Load scheduling profiles.
        """
        profiles = ConfigParser()
        profiles.read(Path.sched_profiles)

        self.sections = []
        ind = 0
        for indx, section in enumerate(profiles.sections()):
            self.sections.append(section)
            self.schedp_name.append_text(section)
            if section == self.start_profile:
                ind = indx

        self.schedp_name.set_active(ind)

        self._check_profile(None)

    def _load_profile(self):
        """
        Load current set schedule profile.
        """
        profile = ConfigParser()
        profile.read(Path.sched_profiles)

        values = {
            "minute": self.cron_minute.set_text,
            "hour": self.cron_hour.set_text,
            "day": self.cron_day.set_text,
            "month": self.cron_month.set_text,
            "weekday": self.cron_weekday.set_text,
        }

        for item in profile.items(self.schedp_name.get_active_text()):
            values[item[0]](item[1])

    def _check_profile(self, event):
        """
        Check if current text in schedp_name combobox is a profile name.
        """
        if self.schedp_name.get_active_text() in self.sections:
            self._load_profile()
        else:
            self.cron_minute.set_text("")
            self.cron_hour.set_text("")
            self.cron_day.set_text("")
            self.cron_month.set_text("")
            self.cron_weekday.set_text("")

    def _save_profile(self, event):
        """
        Save scheduling profile.
        """
        pname = self.schedp_name.get_active_text()
        if not len(pname):
            dlg = HIGAlertDialog(
                self,
                message_format=_(
                    "Scheduling Profile - Error \
while saving"
                ),
                secondary_text=_(
                    "You need to specify a name \
for Profile."
                ),
            )
            dlg.run()
            dlg.destroy()
            return

        parser = CronParser()
        minute = self.cron_minute.get_text()
        hour = self.cron_hour.get_text()
        day = self.cron_day.get_text()
        month = self.cron_month.get_text()
        weekday = self.cron_weekday.get_text()
        try:
            parser.parse_minute(minute)
            parser.parse_hour(hour)
            parser.parse_day(day)
            parser.parse_month(month)
            parser.parse_weekday(weekday)
        except Exception, e:
            dlg = HIGAlertDialog(
                self,
                message_format=_(
                    "Scheduling Profile - Error \
while saving"
                ),
                secondary_text=_(
                    "Check your cron syntax and \
try to save again."
                ),
            )
            dlg.run()
            dlg.destroy()
            return

        # write profile to file
        p_cfg = ConfigParser()
        p_cfg.read(Path.sched_profiles)

        if not p_cfg.has_section(pname):
            new_sec = True
            p_cfg.add_section(pname)
        else:
            new_sec = False

        p_cfg.set(pname, "minute", minute)
        p_cfg.set(pname, "hour", hour)
        p_cfg.set(pname, "day", day)
        p_cfg.set(pname, "month", month)
        p_cfg.set(pname, "weekday", weekday)

        p_cfg.write(open(Path.sched_profiles, "w"))

        if new_sec:  # update daddy scheduling profiles list
            self.daddy._load_pscheds()
class GraphPreferences(HIGWindow):
    """
    Graph Preferences Editor
    """

    def __init__(self, daddy=None):
        HIGWindow.__init__(self)

        self.daddy = daddy # TLGraphToolbar instance
        self.wtitle = _("Graph Preferences Editor")

        # header
        self.title_markup = "<span size='16500' weight='heavy'>%s</span>"
        self.ttitle = HIGEntryLabel("")
        self.ttitle.set_line_wrap(False)
        self.ttitle.set_markup(self.title_markup % self.wtitle)
        self.umit_logo = gtk.Image()
        self.umit_logo.set_from_file(logo)
        # profiles
        self.graph_profile_lbl = HIGEntryLabel(_("Profile"))
        self.graph_profile = gtk.combo_box_new_text()
        # horizontal divisors/balloons
        self.hdivs_lbl = HIGEntryLabel(_("Horizontal divisors"))
        self.hdivs = gtk.SpinButton(gtk.Adjustment(value=5, lower=2, upper=10,
            step_incr=1), 1)
        # arc drawing
        self.draw_arc_lbl = HIGEntryLabel('')
        self.draw_arc_lbl.set_markup(_("<b>Points higlight</b>"))
        self.draw_arc_onsel = gtk.RadioButton(label=_("On Selection"))
        self.draw_arc_always = gtk.RadioButton(self.draw_arc_onsel,
            label=_("Always"))
        self.draw_arc_bounds = gtk.RadioButton(label=_("Boundary points only"))
        self.draw_arc_allpts = gtk.RadioButton(self.draw_arc_bounds,
            label=_("Every point"))
        self.balloons = gtk.CheckButton(_("Show balloons on selection"))
        # vertical divisors
        self.draw_vertdiv = gtk.CheckButton(_("Draw vertical lines"))
        self.draw_vertdiv_dash = gtk.RadioButton(label=_("Dashed"))
        self.draw_vertdiv_solid = gtk.RadioButton(self.draw_vertdiv_dash,
            label=_("Solid"))
        # background fill
        self.bg_gradient = gtk.CheckButton(_("Gradient background"))
        self.bg_gradient_vert = gtk.RadioButton(label=_("Vertical gradient"))
        self.bg_gradient_horiz = gtk.RadioButton(self.bg_gradient_vert,
            label=_("Horizontal gradient"))
        # selection fill
        self.selection_fill = gtk.CheckButton(_("On selection do "
            "progressive fill"))
        self.selection_fill_solid = gtk.RadioButton(label=_("Solid fill"))
        self.selection_fill_gradient = gtk.RadioButton(
            self.selection_fill_solid, label=_("Gradient fill"))
        # bottom buttons
        self.help = HIGButton(stock=gtk.STOCK_HELP)
        self.help.connect('clicked', self._show_help)
        self.apply = HIGButton(stock=gtk.STOCK_APPLY)
        self.apply.connect('clicked', self._save_pref)
        self.cancel = HIGButton(stock=gtk.STOCK_CANCEL)
        self.cancel.connect('clicked', self._exit)
        self.ok = HIGButton(stock=gtk.STOCK_OK)
        self.ok.connect('clicked', self._save_pref_and_leave)


        self.append_profiles()
        start_profile = self.load_options_from_graph()
        self.setup_controls(None, start_profile)

        self.__do_connects()
        self.__set_props()
        self.__do_layout()


    def append_profiles(self):
        """
        Write profiles to combobox.
        """
        for p in profiles:
            self.graph_profile.append_text(p)

        self.graph_profile.set_active(1)


    def graph_attrs(self):
        """
        Tuple of attributes in graph.
        """
        return (
            "hdivisors", "draw_arcs_always", "draw_every_arc",
            "show_balloons", "draw_dashed_vert", "draw_solid_vert",
            "gradient_fill", "gradient_direction", "selection_effect",
            "selection_gradient" )


    def load_options_from_graph(self):
        """
        Load startup graph settings.
        """
        # horizontal divisors
        hdivs = self.daddy.graph_attr("hdivisors") + 1
        # arcs
        draw_arcs_always = int(self.daddy.graph_attr("draw_arcs_always"))
        draw_every_arc = int(self.daddy.graph_attr("draw_every_arc"))
        # balloons
        balloons = self.daddy.graph_attr("show_balloons")
        # vertical lines
        vert_enabled = True
        if self.daddy.graph_attr("draw_dashed_vert"):
            vert_line = 0
        elif self.daddy.graph_attr("draw_solid_vert"):
            vert_line = 1
        else:
            vert_line = -1
            vert_enabled = False
        # widget background
        gradient_bg = True and self.daddy.graph_attr("gradient_fill")
        if not gradient_bg:
            gradient_bg_dir = -1
        else:
            gradient_bg_dir = int(self.daddy.graph_attr("gradient_direction"))
        # selection
        selection_effect = True and self.daddy.graph_attr("selection_effect")
        selection_fill = int(self.daddy.graph_attr("selection_gradient"))

        profile = {"Startup": (
            hdivs, draw_arcs_always, draw_every_arc,
            balloons, vert_enabled, vert_line,
            gradient_bg, gradient_bg_dir,
            selection_effect, selection_fill)}

        return profile


    def setup_controls(self, event, startup=None):
        """
        Enable/Disable controls.
        """
        opt_profiles = (
            _("Standard"), _("Best Performance"), _("Best Visual")
            )

        profile = self.graph_profile.get_active_text()
        indx_active = self.graph_profile.get_active()
        if not profile in opt_profiles: # custom
            return

        # dict with default values for each option in this window.
        profiles_d = {
            _("Standard"): (5, 0, 1, True, False, -1, False, -1, True, 0),
            _("Best Performance"): (3, 0, 0, True, False, -1, False, -1,
                False, 0),
            _("Best Visual"): (5, 0, 1, True, True, 0, True, 0, True, 1)
            }

        if startup:
            found_profile = False
            for p, values in profiles_d.items():
                if startup["Startup"] == values:
                    index_profile = profiles.index(p)
                    self.graph_profile.set_active(index_profile)
                    indx_active = self.graph_profile.get_active()
                    profile = p
                    found_profile = True
                    break

            if not found_profile: # custom
                indx_active = 0
                profile = _("Custom")
                self.graph_profile.set_active(indx_active)
                temp = { }
                temp[_("Custom")] = startup["Startup"]
                profiles_d.update(temp)


        controls = (self.hdivs, (self.draw_arc_onsel, self.draw_arc_always),
                    (self.draw_arc_bounds, self.draw_arc_allpts),
                    self.balloons, self.draw_vertdiv, (self.draw_vertdiv_dash,
                    self.draw_vertdiv_solid), self.bg_gradient,
                    (self.bg_gradient_vert, self.bg_gradient_horiz),
                    self.selection_fill, (self.selection_fill_solid,
                    self.selection_fill_gradient))

        for indx, control in enumerate(controls):
            value = profiles_d[profile][indx]

            if value >= 2: # it is spinbutton
                control.set_value(float(value))
            elif isinstance(value, bool): # checkbutton
                control.set_active(value)
            elif value != -1: # radiobutton
                control[value].set_active(True)


        checkbtns = (self.draw_vertdiv, self.bg_gradient)
        methods = (self._vertdiv_changed, self._bgfill_changed)

        for indx, checkbtn in enumerate(checkbtns):
            methods[indx](checkbtn.get_active(), indx_active)

        return True


    def _vertdiv_changed(self, event, custom=0):
        """
        Vertical divisors enabled/disabled.
        """
        status = self.get_status(event)

        self.draw_vertdiv_dash.set_sensitive(status)
        self.draw_vertdiv_solid.set_sensitive(status)

        self.graph_profile.set_active(custom)


    def _bgfill_changed(self, event, custom=0):
        """
        Gradient background fill enabled/disabled.
        """
        status = self.get_status(event)

        self.bg_gradient_vert.set_sensitive(status)
        self.bg_gradient_horiz.set_sensitive(status)

        self.graph_profile.set_active(custom)


    def get_status(self, event):
        """
        Get event status.
        """
        if isinstance(event, bool):
            status = event # event generated by profile change
        else:
            status = event.get_active() # event generated by mouse click

        return status


    def _show_help(self, event):
        """
        Show help for Graph Preferences.
        """


    def _save_pref(self, event):
        """
        Save preferences.
        """
        profile = self.graph_profile.get_active_text()

        cmds = {
            _("Standard"): "standard_mode",
            _("Best Performance"): "speedup_performance",
            _("Best Visual"): "best_visual" }

        if profile != _("Custom"):
            self.daddy.change_graph_mode = cmds[profile]
            return

        controls = (self.hdivs, self.draw_arc_always, self.draw_arc_allpts,
                    self.balloons, (self.draw_vertdiv, self.draw_vertdiv_dash,
                    self.draw_vertdiv_solid), self.bg_gradient,
                    self.bg_gradient_horiz, self.selection_fill,
                    self.selection_fill_gradient)

        indx = 0
        for control in controls:
            if isinstance(control, tuple): # group of controls
                enable = True
                if not control[0].get_active():
                    enable = False

                for c in control[1:]:
                    if enable == False:
                        self.daddy.change_graph_attr = (
                            self.graph_attrs()[indx], False)
                    else:
                        self.daddy.change_graph_attr = (
                            self.graph_attrs()[indx], c.get_active())
                    indx += 1

                continue

            elif hasattr(control, "get_active"): # radio/checkbutton
                self.daddy.change_graph_attr = (
                    self.graph_attrs()[indx], control.get_active())

            elif hasattr(control, "set_width_chars"): # spinbutton
                nhdiv = int(control.get_text())
                self.daddy.change_graph_attr = self.graph_attrs()[indx], nhdiv

            indx += 1

        self.daddy.update_graph()


    def _save_pref_and_leave(self, event):
        """
        Saves preferences and close window.
        """
        self._save_pref(None)
        self._exit(None)


    def _exit(self, event):
        """
        Close window.
        """
        self.destroy()


    def __do_connects(self):
        """
        Connect signals.
        """
        self.hdivs.connect('value-changed',
            lambda c: self.graph_profile.set_active(0))

        self.draw_arc_always.connect('clicked',
            lambda c: self.graph_profile.set_active(0))
        self.draw_arc_bounds.connect('clicked',
            lambda c: self.graph_profile.set_active(0))
        self.draw_arc_allpts.connect('clicked',
            lambda c: self.graph_profile.set_active(0))
        self.balloons.connect('toggled',
            lambda c: self.graph_profile.set_active(0))

        self.draw_vertdiv.connect('toggled', self._vertdiv_changed)
        self.draw_vertdiv_dash.connect('clicked',
            lambda c: self.graph_profile.set_active(0))
        self.draw_vertdiv_solid.connect('clicked',
            lambda c: self.graph_profile.set_active(0))

        self.bg_gradient.connect('toggled', self._bgfill_changed)
        self.bg_gradient_vert.connect('clicked',
            lambda c: self.graph_profile.set_active(0))
        self.bg_gradient_horiz.connect('clicked',
            lambda c: self.graph_profile.set_active(0))

        self.selection_fill.connect('toggled',
            lambda c: self.graph_profile.set_active(0))
        self.selection_fill_solid.connect('clicked',
            lambda c: self.graph_profile.set_active(0))
        self.selection_fill_gradient.connect('clicked',
            lambda c: self.graph_profile.set_active(0))

        self.graph_profile.connect('changed', self.setup_controls)


    def __set_props(self):
        """
        Set window properties.
        """
        self.set_title(self.wtitle)


    def __do_layout(self):
        """
        Layout widgets in window.
        """

        def left_padding(widget):
            """
            Add left padding for a widget.
            """
            left_padding_align = gtk.Alignment(0.5, 0.5, 1, 1)
            left_padding_align.set_padding(0, 0, 12, 0)
            left_padding_align.add(widget)
            return left_padding_align


        main_vbox = HIGVBox()
        main_vbox.set_border_width(5)
        main_vbox.set_spacing(12)
        header_hbox = HIGHBox()
        profile_hbox = HIGHBox()
        hdivs_hbox = HIGHBox()
        arcdraw_vbox = HIGVBox()
        vdivs_vbox = HIGVBox()
        bgfill_vbox = HIGVBox()
        selectfill_vbox = HIGVBox()
        btns_hbox = HIGHBox()

        # header
        header_hbox._pack_expand_fill(self.ttitle)
        header_hbox._pack_noexpand_nofill(self.umit_logo)

        # profiles
        profile_hbox._pack_noexpand_nofill(self.graph_profile_lbl)
        profile_hbox._pack_noexpand_nofill(self.graph_profile)

        # horizontal divisors
        hdivs_hbox._pack_noexpand_nofill(self.hdivs_lbl)
        hdivs_hbox._pack_noexpand_nofill(self.hdivs)

        # arc drawing
        arcdraw_vbox._pack_noexpand_nofill(self.draw_arc_lbl)

        arcdraw_when = HIGHBox()
        arcdraw_when._pack_noexpand_nofill(self.draw_arc_onsel)
        arcdraw_when._pack_noexpand_nofill(self.draw_arc_always)

        arcdraw_where = HIGHBox()
        arcdraw_where._pack_noexpand_nofill(self.draw_arc_bounds)
        arcdraw_where._pack_noexpand_nofill(self.draw_arc_allpts)

        arcdraw_vbox._pack_noexpand_nofill(left_padding(arcdraw_when))
        arcdraw_vbox._pack_noexpand_nofill(left_padding(arcdraw_where))
        arcdraw_vbox._pack_noexpand_nofill(left_padding(self.balloons))

        # vertical divisors
        vdivs_vbox._pack_noexpand_nofill(self.draw_vertdiv)

        vdivs_kind = HIGHBox()
        vdivs_kind._pack_noexpand_nofill(self.draw_vertdiv_dash)
        vdivs_kind._pack_noexpand_nofill(self.draw_vertdiv_solid)

        vdivs_vbox._pack_noexpand_nofill(left_padding(vdivs_kind))

        # background fill
        bgfill_vbox._pack_noexpand_nofill(self.bg_gradient)

        bgfill_gtype = HIGHBox()
        bgfill_gtype._pack_noexpand_nofill(self.bg_gradient_vert)
        bgfill_gtype._pack_noexpand_nofill(self.bg_gradient_horiz)

        bgfill_vbox._pack_noexpand_nofill(left_padding(bgfill_gtype))

        # selection fill
        selectfill_vbox._pack_noexpand_nofill(self.selection_fill)

        selectfill_kind = HIGHBox()
        selectfill_kind._pack_noexpand_nofill(self.selection_fill_solid)
        selectfill_kind._pack_noexpand_nofill(self.selection_fill_gradient)

        selectfill_vbox._pack_noexpand_nofill(left_padding(selectfill_kind))

        # bottom buttons
        btns_hbox.set_homogeneous(True)
        btns_hbox._pack_expand_fill(self.help)
        btns_hbox._pack_expand_fill(hig_box_space_holder())
        btns_hbox._pack_expand_fill(self.apply)
        btns_hbox._pack_expand_fill(self.cancel)
        btns_hbox._pack_expand_fill(self.ok)


        main_vbox._pack_noexpand_nofill(header_hbox)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(profile_hbox)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(hdivs_hbox)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(arcdraw_vbox)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(vdivs_vbox)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(bgfill_vbox)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(selectfill_vbox)
        main_vbox.pack_end(btns_hbox, False, False, 0)
        main_vbox.pack_end(gtk.HSeparator(), False, False, 0)
        self.add(main_vbox)
Exemplo n.º 4
0
class NewInventory(HIGWindow):
    """
    A window for creating new or editing existing Inventories.
    """
    def __init__(self, inventory=None, edit_mode=False):
        """
        If you want to load an inventory at startup, pass it to inventory.
        If you want to run this in edit mode, set to True edit_mode.
        """
        HIGWindow.__init__(self)

        self.schemawin = None
        self.discoverywin = None
        self.edit_mode = edit_mode
        if edit_mode:
            self.wtitle = _("Editing Inventory")
        else:
            self.wtitle = _("New Inventory")

        # header
        self.title_markup = "<span size='16500' weight='heavy'>%s</span>"
        self.ttitle = HIGEntryLabel("")
        self.ttitle.set_line_wrap(False)
        self.ttitle.set_markup(self.title_markup % self.wtitle)
        self.umit_logo = gtk.Image()
        self.umit_logo.set_from_file(logo)
        # inventory
        self.invname_lbl = HIGEntryLabel(_("Inventory's name"))
        self.invname = gtk.Entry()
        self.invname.connect('changed', self._check_invname)
        self.invname_inuse = HIGEntryLabel(_("in use"))
        self.invname_inuse.set_sensitive(False)
        self.invenabled = gtk.CheckButton(_("Enabled"))
        self.invenabled.set_active(True)
        # scan command
        self.scandefault = gtk.CheckButton(_("Use default scan options"))
        img_info = gtk.Image()
        img_info.set_from_stock(gtk.STOCK_INFO, gtk.ICON_SIZE_MENU)
        self.scandefault_tip = gtk.EventBox()
        self.scandefault_tip.add(img_info)

        self.scanadv = gtk.Expander(_("Use advanced scan options"))
        self.scan_name_lbl = HIGEntryLabel(_("Scan Profile"))
        self.scan_name = ProfileCombo()
        self.scan_name.update()
        self.scan_name.set_active(0)
        self.scan_name.connect('changed', self._set_scan_command)
        self.cmd_wizard = gtk.Button(stock=gtk.STOCK_CONVERT)
        blbl = self.cmd_wizard.get_children()[0].get_children(
        )[0].get_children()[1]
        blbl.set_text(_("Command Wizard"))
        self.cmd_wizard.connect('clicked', self._open_cmd_wizard)

        self.scan_command_lbl = HIGEntryLabel(_("Command"))
        self.scan_command = gtk.Entry()
        self.scan_command.connect('changed', self._set_scan_type)
        self._set_scan_command(None)
        self.scandefault.set_active(True)
        # scan target
        self.scantarget_lbl = HIGEntryLabel(_("Scan target"))
        self.scantarget = gtk.Entry()
        self.scantarget_discovery = HIGButton(_("Use host discovery"))
        self.scantarget_discovery.connect('clicked', self._open_host_discovery)
        # scheduling profiles
        self.sched_name_lbl = HIGEntryLabel(_("Scheduling Profile"))
        self.sched_name = gtk.combo_box_new_text()
        self.sched_name_edit = gtk.Button(stock=gtk.STOCK_EDIT)
        blbl = self.sched_name_edit.get_children()[0].get_children(
        )[0].get_children()[1]
        blbl.set_text(_("Edit Profiles"))
        self.sched_name_edit.connect('clicked', self._edit_schedprofiles)
        # bottom buttons
        self.help = HIGButton(stock=gtk.STOCK_HELP)
        self.help.connect('clicked', self._show_help)
        self.cancel = HIGButton(stock=gtk.STOCK_CANCEL)
        self.cancel.connect('clicked', self._exit)
        self.ok = HIGButton(stock=gtk.STOCK_OK)
        self.ok.connect('clicked', self._save_inventory_and_leave)

        self.tooltips = gtk.Tooltips()
        self.tooltips.set_tip(self.scandefault_tip,
                              _("nmap -T Aggressive -sV -n -O -v target"))

        # disable controls if edit_mode=True
        if edit_mode:
            self.invname.set_sensitive(False)
            self.scandefault.set_sensitive(False)
            self.scandefault_tip.set_sensitive(False)
            self.scanadv.set_sensitive(False)
            self.scan_name.set_sensitive(False)
            self.scan_command.set_sensitive(False)
            self.scantarget_lbl.set_sensitive(False)
            self.scantarget.set_sensitive(False)
            self.scantarget_discovery.set_sensitive(False)

        self.connect('destroy', self._exit)
        self.profile_running = None  # no SchedProfileEditor instance is running.
        self.load_schemas()
        self._load_pscheds()

        # load an inventory if especified
        self.loaded_command = None
        if inventory:
            self.load_inventory(inventory)

        self.__set_props()
        self.__do_layout()

    def load_inventory(self, inventory):
        """
        Load inventory.
        """
        inv = ConfigParser()
        inv.read(Path.sched_schemas)

        if not inv.has_section(inventory):
            dlg = NoScheduleDlg()
            dlg.run()
            dlg.destroy()
            raise NoInventory(inventory)

        self.invname.set_text(inventory)
        for item in inv.items(inventory):
            if item[0] == 'profile':
                pindx = self.profiles.index(item[1])
                self.sched_name.set_active(pindx)
            if item[0] == 'enabled':
                self.invenabled.set_active(int(item[1]))
            if item[0] == 'command':
                self.loaded_command = item[1]

    def load_schemas(self):
        """
        Load scheduler schemas profiles.
        """
        schemas = ConfigParser()
        schemas.read(Path.sched_schemas)

        self.sections = []
        for section in schemas.sections():
            self.sections.append(section)

    def _load_pscheds(self):
        """
        Load scheduling profiles.
        """
        pscheds = ConfigParser()
        pscheds.read(Path.sched_profiles)

        self.profiles = []
        self.sched_name.get_model().clear()
        for section in pscheds.sections():
            self.sched_name.append_text(section)
            self.profiles.append(section)

        self.sched_name.set_active(0)

    def _check_invname(self, event):
        """
        Check if Inventory's name isn't in use.
        """
        if self.invname.get_text() and \
           (self.invname.get_text() in self.sections) and \
            not self.edit_mode:
            self.invname_inuse.set_sensitive(True)
        else:
            self.invname_inuse.set_sensitive(False)

    def _edit_schedprofiles(self, event):
        """
        Open Scheduling Profiles Editor.
        """
        if self.profile_running:
            return

        win = SchedProfileEditor(self, self.sched_name.get_active_text())
        win.show_all()
        self.profile_running = win

    def _set_scan_type(self, event):
        """
        When scan command is changed, unset "Default scan options" if it is
        selected.
        """
        if self.scandefault.get_active():
            self.scandefault.set_active(False)

    def _open_cmd_wizard(self, event):
        """
        Run command wizard window and update combobox when it finishes.
        """
        def update_scan_profiles(wwin):
            self.scan_name.update()

        w = Wizard()
        w.show_all()
        w.connect('destroy', update_scan_profiles)

    def _open_host_discovery(self, event):
        """
        Open host discovery window.
        """
        if self.discoverywin:
            return

        w = HostDiscovery(self)
        w.show_all()

        self.discoverywin = w

    def get_discoverywin(self):
        """
        Get HostDiscovery running instance.
        """
        return self.__discoverywin

    def set_discoverywin(self, win):
        """
        Set HostDiscovery instance.
        """
        self.__discoverywin = win

    def get_schemawin(self):
        """
        Get scheduelr schemas editor running instance.
        """
        return self.__schemawin

    def set_schemawin(self, win):
        """
        Set scheduler schemas editor instance.
        """
        self.__schemawin = win

    def get_profile_running(self):
        """
        Get profile editor running instance.
        """
        return self.__profilerunning

    def set_profile_running(self, running):
        """
        Set profile editor instance.
        """
        self.__profilerunning = running

    def _save_inventory(self, event):
        """
        Save inventory.
        """
        target = self.scantarget.get_text()
        invname = self.invname.get_text()
        notinuse = (self.invname_inuse.state == gtk.STATE_INSENSITIVE)
        command_adv = self.scan_command.get_text()

        # checking for errors
        if not notinuse or not len(invname) and not self.edit_mode:
            dlg = HIGAlertDialog(
                self,
                message_format=_("New Inventory - Error while creating."),
                secondary_text=_("You tried to use an existing Inventory "
                                 "name or you didn't specify one."))

            dlg.run()
            dlg.destroy()
            return 0

        if not len(target) and not self.edit_mode:
            dlg = HIGAlertDialog(
                self,
                message_format=_("New Inventory - Error  while creating."),
                secondary_text=_("You didn't specify any target."))

            dlg.run()
            dlg.destroy()
            return 0

        if not self.edit_mode:
            if Address_Checker(target) == "IPV4":
                option = ""
            elif Address_Checker(target) == "IPV6":
                option = "-6 "
            elif Address_Checker(target) == "MAC":
                option = ""
            else:
                option = ""
                dlg = HIGAlertDialog(
                    self,
                    message_format=_("New Inentory - Error While Creating."),
                    secondary_text=_("You need to enter correct address either"
                                     "IPV4 or IPv6 or MAC address"))
                dlg.run()
                dlg.destroy()
                return 0


        if not len(command_adv) and not self.scandefault.get_active() \
            and not self.edit_mode:
            dlg = HIGAlertDialog(
                self,
                message_format=_("New Inventory - Error while creating."),
                secondary_text=_("You need to toggle \"Use default scan "
                                 "options\" or specify a command."))

            dlg.run()
            dlg.destroy()
            return 0
        # end error checking

        if self.scandefault.get_active() and not self.edit_mode:
            command = "nmap -T Aggressive -sV -n -O -v " + option + target
        elif not self.edit_mode:
            target_cmd = "<target>"
            target_pos = command_adv.find(target_cmd)
            if target_pos != -1:
                start = target_pos
                end = target_pos + len(target_cmd)
                command = command_adv[:start] + option + target + command_adv[
                    end:]
            else:
                dlg = HIGAlertDialog(
                    self,
                    message_format=_("New Inventory - Error while creating."),
                    secondary_text=_(
                        "It seems you removed <target> from the "
                        "Scan command entry, you need to leave it somewhere "
                        "there."))

                dlg.run()
                dlg.destroy()
                return 0

        schedule = self.sched_name.get_active_text()
        enabled = int(self.invenabled.get_active())
        # write inventory to schema's file
        s_cfg = ConfigParser()
        s_cfg.read(Path.sched_schemas)

        if not s_cfg.has_section(invname):
            new_sec = True
            s_cfg.add_section(invname)
        elif self.edit_mode:
            new_sec = False
        else:
            print "How the hell did we get here?!"
            print "Report as BUG"
            return 0

        if new_sec:
            # New Section
            s_cfg.set(invname, 'profile', schedule)
            s_cfg.set(invname, 'command', command)
            s_cfg.set(invname, 'enabled', enabled)
            s_cfg.set(invname, 'addtoinv', '2')
            s_cfg.set(invname, 'saveto', '')
            s_cfg.set(invname, 'mailto', '')
            s_cfg.set(invname, 'smtp', '')
        else:
            # Edit Mode
            s_cfg.set(invname, 'profile', schedule)
            s_cfg.set(invname, 'enabled', enabled)
            #here i have to put check for scan target field
            command_text = self.cmd_entry.get_text()
            if command_text.find("nmap") == -1:
                dlg = HIGAlertDialog(
                    self,
                    message_format=_("Edit Inventory - Error while creating."),
                    secondary_text=_(
                        "It seems you have not entered namp in "
                        "command field. enter correct command with target."))
                dlg.run()
                dlg.destroy()
                return 0

            s_cfg.set(invname, 'command', command_text)

        s_cfg.write(open(Path.sched_schemas, 'w'))

        self.load_schemas()

        return 1

    def _save_inventory_and_leave(self, event):
        """
        Save Inventory and close window.
        """
        close_win = self._save_inventory(None)
        if close_win:
            self._exit(None)

    def _set_scan_command(self, event):
        """
        Set scan command based on chosen profile.
        """
        profile = self.scan_name.get_selected_profile()
        cmd_profile = CommandProfile()
        command = cmd_profile.get_command(profile)
        self.scan_command.set_text(command % '<target>')

    def _show_help(self, event):
        """
        Show help for creating a New Inventory.
        """
        pass

    def _exit(self, event):
        """
        Close window.
        """
        if self.schemawin:
            self.schemawin._exit(None)

        if self.profile_running:
            self.profile_running._exit(None)

        self.destroy()

    def __set_props(self):
        """
        Set window properties.
        """
        self.set_title(self.wtitle)

    def __do_layout(self):
        """
        Layout widgets.
        """
        main_vbox = HIGVBox()
        main_vbox.set_border_width(5)
        main_vbox.set_spacing(12)
        header_hbox = HIGHBox()
        invname_hbox = HIGHBox()
        scan_hbox = HIGHBox()
        scanadv_hbox = HIGHBox()
        scantarget_hbox = HIGHBox()
        sched_box = HIGHBox()
        btns_hbox = HIGHBox()

        # header
        header_hbox._pack_expand_fill(self.ttitle)
        header_hbox._pack_noexpand_nofill(self.umit_logo)
        # inventory's name
        invname_hbox._pack_noexpand_nofill(self.invname_lbl)
        invname_hbox._pack_expand_fill(self.invname)
        invname_hbox._pack_noexpand_nofill(self.invname_inuse)
        invname_hbox._pack_noexpand_nofill(self.invenabled)
        # scan command
        scan_hbox._pack_noexpand_nofill(self.scandefault)
        scan_hbox._pack_noexpand_nofill(self.scandefault_tip)
        scanadv_hbox._pack_expand_fill(self.scanadv)

        adv_box = HIGVBox()
        scanadv_align = gtk.Alignment(0.5, 0.5, 1, 1)
        scanadv_align.set_padding(6, 0, 12, 0)
        scanname_box = HIGHBox()
        scanname_box._pack_noexpand_nofill(self.scan_name_lbl)
        scanname_box._pack_expand_fill(self.scan_name)
        scanname_box._pack_noexpand_nofill(self.cmd_wizard)
        adv_box.add(scanname_box)
        scancmd_box = HIGHBox()
        scancmd_box._pack_noexpand_nofill(self.scan_command_lbl)
        scancmd_box._pack_expand_fill(self.scan_command)
        adv_box.add(scancmd_box)

        scanadv_align.add(adv_box)
        self.scanadv.add(scanadv_align)
        # scan target
        scantarget_hbox._pack_noexpand_nofill(self.scantarget_lbl)
        scantarget_hbox._pack_expand_fill(self.scantarget)
        scantarget_hbox._pack_noexpand_nofill(self.scantarget_discovery)
        # scheduling profiles
        sched_box._pack_noexpand_nofill(self.sched_name_lbl)
        sched_box._pack_expand_fill(self.sched_name)
        sched_box._pack_noexpand_nofill(self.sched_name_edit)
        # bottom buttons
        btns_hbox.set_homogeneous(True)
        btns_hbox._pack_expand_fill(self.help)
        btns_hbox._pack_expand_fill(hig_box_space_holder())
        btns_hbox._pack_expand_fill(self.cancel)
        btns_hbox._pack_expand_fill(self.ok)

        main_vbox._pack_noexpand_nofill(header_hbox)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(invname_hbox)
        main_vbox._pack_noexpand_nofill(scan_hbox)
        main_vbox._pack_noexpand_nofill(scanadv_hbox)
        main_vbox._pack_noexpand_nofill(scantarget_hbox)

        if self.loaded_command and self.edit_mode:
            view_cmd_box = HIGHBox()
            view_cmd_box._pack_noexpand_nofill(gtk.Label(_("Command")))
            # XXX Why don't reuse scan_command?
            self.cmd_entry = gtk.Entry()
            self.cmd_entry.set_text(self.loaded_command)
            view_cmd_box._pack_expand_fill(self.cmd_entry)
            img_info = gtk.Image()
            img_info.set_from_stock(gtk.STOCK_INFO, gtk.ICON_SIZE_MENU)
            eb = gtk.EventBox()
            eb.add(img_info)
            self.tooltips.set_tip(eb, _("Changes in command won't be saved!"))
            view_cmd_box.pack_end(eb, False, False, 0)
            main_vbox._pack_noexpand_nofill(view_cmd_box)

        main_vbox._pack_noexpand_nofill(sched_box)
        main_vbox.pack_end(btns_hbox, False, False, 0)
        main_vbox.pack_end(gtk.HSeparator(), False, False, 0)

        self.add(main_vbox)

    # Properties
    schemawin = property(get_schemawin, set_schemawin)
    discoverywin = property(get_discoverywin, set_discoverywin)
    profile_running = property(get_profile_running, set_profile_running)
Exemplo n.º 5
0
class SchedSchemaEditor(HIGWindow):
    """
    Scheduler Schemas Editor
    """

    def __init__(self, daddy=None):
        HIGWindow.__init__(self)

        self.daddy = daddy
        self.wtitle = _("Scan Scheduler Editor")

        # header
        self.title_markup = "<span size='16500' weight='heavy'>%s</span>"
        self.ttitle = HIGEntryLabel("")
        self.ttitle.set_line_wrap(False)
        self.ttitle.set_markup(self.title_markup % self.wtitle)
        self.umit_logo = gtk.Image()
        self.umit_logo.set_from_file(logo)
        # schemas name
        self.schema_name_lbl = HIGEntryLabel(_("Schema Name"))
        self.schema_name = gtk.combo_box_entry_new_text()
        self.schema_name.connect("changed", self._check_schema)
        # target and scan profiles
        # self.target_lbl = HIGEntryLabel(_("Target"))
        # self.target = gtk.Entry()
        self.scan_name_lbl = HIGEntryLabel(_("Scan Profile"))
        self.scan_name = ProfileCombo()
        self.scan_name.update()
        self.scan_name.set_active(0)
        self.scan_name.connect("changed", self._set_scan_command)
        # scan command
        self.scan_command_lbl = HIGEntryLabel(_("Command"))
        self.scan_command = gtk.Entry()
        # scheduling profile
        self.sched_name_lbl = HIGEntryLabel(_("Scheduling Profile"))
        self.sched_name = gtk.combo_box_new_text()
        self.sched_name_edit = gtk.Button(stock=gtk.STOCK_EDIT)
        blbl = self.sched_name_edit.get_children()[0].get_children()[0].get_children()[1]
        blbl.set_text(_("Edit Profiles"))
        self.sched_name_edit.connect("clicked", self._edit_schedprofiles)
        # schema settings
        self.schema_sett_frame = HIGFrame()
        self.setting_saveto = gtk.CheckButton(_("Save outputs to"))
        self.setting_saveto_entry = gtk.Entry()
        self.setting_saveto_browse = gtk.Button(_("..."))
        self.setting_saveto_browse.connect("clicked", self._select_saveto)
        self.setting_mailto = gtk.CheckButton(_("Send output to email"))
        self.setting_mailto_entry = gtk.Entry()
        self.setting_smtp_lbl = HIGEntryLabel(_("SMTP Schema"))
        self.setting_smtp = gtk.combo_box_new_text()
        self.setting_addtoinv = gtk.CheckButton(_("Add to the Inventory"))
        self.setting_enabled = gtk.CheckButton(_("Enabled"))
        # bottom buttons
        self.help = HIGButton(stock=gtk.STOCK_HELP)
        self.help.connect("clicked", self._show_help)
        self.apply = HIGButton(stock=gtk.STOCK_APPLY)
        self.apply.connect("clicked", self._save_schema)
        self.cancel = HIGButton(stock=gtk.STOCK_CANCEL)
        self.cancel.connect("clicked", self._exit)
        self.ok = HIGButton(stock=gtk.STOCK_OK)
        self.ok.connect("clicked", self._save_schema_and_leave)

        self.load_smtp_schemas()
        self._set_scan_command(None)
        self.profile_running = None  # no SchedProfileEditor instance is running.
        self._load_pscheds()
        self.load_schemas()

        self.__set_props()
        self.__do_layout()

        self.connect("destroy", self._exit)

    def load_smtp_schemas(self):
        """
        Load smtp profiles.
        """
        schemas = ConfigParser()
        schemas.read(Path.smtp_schemas)

        self.smtp_sections = []
        self.setting_smtp.get_model().clear()
        for section in schemas.sections():
            self.smtp_sections.append(section)
            self.setting_smtp.append_text(section)

        self.setting_smtp.set_active(0)

    def load_schemas(self):
        """
        Load schemas profiles.
        """
        schemas = ConfigParser()
        schemas.read(Path.sched_schemas)

        self.sections = []
        self.schema_name.get_model().clear()
        for section in schemas.sections():
            self.sections.append(section)
            self.schema_name.append_text(section)

        self.schema_name.set_active(0)
        self._check_schema(None)

    def _load_schema(self):
        """
        Load current set schedule schema.
        """
        schema = ConfigParser()
        schema.read(Path.sched_schemas)

        values = {
            "command": self.scan_command.set_text,
            "saveto": self.setting_saveto_entry.set_text,
            "mailto": self.setting_mailto_entry.set_text,
        }
        enable = {"saveto": self.setting_saveto.set_active, "mailto": self.setting_mailto.set_active}

        for item in schema.items(self.schema_name.get_active_text()):
            if item[0] == "addtoinv":
                self.setting_addtoinv.set_active(int(item[1]))
                if item[1] == "2":
                    self.apply.set_sensitive(False)
                    self.ok.set_sensitive(False)
                else:
                    self.apply.set_sensitive(True)
                    self.ok.set_sensitive(True)
            elif item[0] == "enabled":
                self.setting_enabled.set_active(int(item[1]))
            elif item[0] == "profile":
                pindx = self.profiles.index(item[1])
                self.sched_name.set_active(pindx)
            elif item[0] == "smtp":
                if item[1]:
                    pindx = self.smtp_sections.index(item[1])
                    self.setting_smtp.set_active(pindx)
            else:
                values[item[0]](item[1])
                if item[0] in ("saveto", "mailto"):
                    if len(item[1]):
                        enable[item[0]](True)
                    else:
                        enable[item[0]](False)

    def _check_schema(self, event):
        """
        Check if current text in schema_name combobox is a schema name.
        """
        if self.schema_name.get_active_text() in self.sections:
            # load schema
            self._load_schema()
        else:
            # reset to default values
            self.apply.set_sensitive(True)
            self.ok.set_sensitive(True)
            self.setting_addtoinv.set_active(False)
            self.setting_enabled.set_active(False)
            self.setting_mailto.set_active(False)
            self.setting_mailto_entry.set_text("")
            self.setting_saveto.set_active(False)
            self.setting_saveto_entry.set_text("")

        self.schema_sett_frame._set_label(self.schema_name.get_active_text() + " - Settings")

    def _set_scan_command(self, event):
        """
        Set scan command based on chosen profile.
        """
        profile = self.scan_name.get_selected_profile()
        cmd_profile = CommandProfile()
        command = cmd_profile.get_command(profile)
        self.scan_command.set_text(command % "<target>")

    def _load_pscheds(self):
        """
        Load scheduling profiles.
        """
        pscheds = ConfigParser()
        pscheds.read(Path.sched_profiles)

        self.profiles = []
        self.sched_name.get_model().clear()
        for section in pscheds.sections():
            self.sched_name.append_text(section)
            self.profiles.append(section)

        self.sched_name.set_active(0)

    def _edit_schedprofiles(self, event):
        """
        Open Scheduling Profiles Editor.
        """
        if self.profile_running:
            return

        win = SchedProfileEditor(self, self.sched_name.get_active_text())
        win.show_all()
        self.profile_running = win

    def _select_saveto(self, event):
        """
        Select directory to save file.
        """
        dir_chooser = DirectoryChooserDialog(_("Select a directory"))

        dir_chooser.run()
        dir_chosen = dir_chooser.get_filename()
        dir_chooser.destroy()
        self.setting_saveto_entry.set_text(dir_chosen)

    def _save_schema(self, event):
        """
        Save current schema.
        """
        schema = self.schema_name.get_active_text()
        command = self.scan_command.get_text()
        schedule = self.sched_name.get_active_text()
        mailto = self.setting_mailto.get_active()

        if not schema or not schedule or not command or "<target>" in command:
            dlg = HIGAlertDialog(
                self,
                message_format=_(
                    "Scheduling Schema - Error\
 while saving."
                ),
                secondary_text=_(
                    'There is some error in at \
least one of the following fields: "Schema name", "Command" or "Scheduling\
 Profile"\n\nCheck if "Schema name" is not empty.\nCheck if "Command" does\
 contain "<target>" on it.\nCheck if there is some "Scheduling Profile" \
selected.'
                ),
            )

            dlg.run()
            dlg.destroy()
            return

        if mailto and not self.setting_smtp.get_active_text():
            dlg = HIGAlertDialog(
                self,
                message_format=_(
                    "Scheduling Schema - Error\
 while saving."
                ),
                secondary_text=_(
                    "You need to create a \
a SMTP Schema for sending email."
                ),
            )

            dlg.run()
            dlg.destroy()
            return

        # check for output existance
        if self.setting_saveto.get_active() and not os.path.isdir(self.setting_saveto_entry.get_text()):

            dlg = HIGAlertDialog(
                self,
                message_format=_(
                    "Scheduling Schema - Error\
 while saving."
                ),
                secondary_text=_(
                    "You especified an invalid \
directory to save scans output."
                ),
            )

            dlg.run()
            dlg.destroy()
            return

        # write schema to file
        s_cfg = ConfigParser()
        s_cfg.read(Path.sched_schemas)

        if not s_cfg.has_section(schema):
            new_sec = True
            s_cfg.add_section(schema)
        else:
            new_sec = False

        s_cfg.set(schema, "profile", schedule)
        s_cfg.set(schema, "command", command)
        if self.setting_enabled.get_active():
            s_cfg.set(schema, "enabled", "1")
        else:
            s_cfg.set(schema, "enabled", "0")
        if self.setting_addtoinv.get_active():
            s_cfg.set(schema, "addtoinv", "1")
        else:
            s_cfg.set(schema, "addtoinv", "0")
        if self.setting_saveto.get_active():
            s_cfg.set(schema, "saveto", self.setting_saveto_entry.get_text())
        else:
            s_cfg.set(schema, "saveto", "")
        if mailto:
            s_cfg.set(schema, "mailto", self.setting_mailto_entry.get_text())
            s_cfg.set(schema, "smtp", self.setting_smtp.get_active_text())
        else:
            s_cfg.set(schema, "mailto", "")
            s_cfg.set(schema, "smtp", "")

        s_cfg.write(open(Path.sched_schemas, "w"))

        if new_sec:
            self.load_schemas()

        if self.daddy:
            self.daddy.load_schemas()

    def _save_schema_and_leave(self, event):
        """
        Save current schema and close editor.
        """
        self._save_schema(None)
        self._exit(None)

    def _show_help(self, event):
        """
        Show help for Scan Scheduler Editor.
        """
        show_help(self, "scheduler.html#setting-up-a-schedule")

    def __set_props(self):
        """
        Set window properties.
        """
        self.set_title(self.wtitle)
        self.set_default_size(440, -1)

    def __do_layout(self):
        """
        Layout widgets in window.
        """
        main_vbox = HIGVBox()
        main_vbox.set_border_width(5)
        main_vbox.set_spacing(12)
        header_hbox = HIGHBox()
        schema_table = HIGTable()
        schedsn_hbox = HIGHBox()
        sett_table = HIGTable()
        btns_hbox = HIGHBox()

        header_hbox._pack_expand_fill(self.ttitle)
        header_hbox._pack_noexpand_nofill(self.umit_logo)

        # schema name
        schema_table.attach_label(self.schema_name_lbl, 0, 1, 0, 1)
        schema_table.attach_entry(self.schema_name, 1, 2, 0, 1)

        # target and scan profile
        schema_table.attach_label(self.scan_name_lbl, 0, 1, 1, 2)
        schema_table.attach_entry(self.scan_name, 1, 2, 1, 2)

        # scan command
        schema_table.attach_label(self.scan_command_lbl, 0, 1, 2, 3)
        schema_table.attach_label(self.scan_command, 1, 2, 2, 3)

        # scheduling profile
        schedsn_hbox._pack_expand_fill(self.sched_name)
        schedsn_hbox._pack_noexpand_nofill(self.sched_name_edit)

        schema_table.attach_label(self.sched_name_lbl, 0, 1, 3, 4)
        schema_table.attach_entry(schedsn_hbox, 1, 2, 3, 4)

        # settings frame
        settings_align = gtk.Alignment(0.5, 0.5, 1, 1)
        settings_align.set_padding(6, 0, 12, 0)
        schemasett_hbox = HIGVBox()

        # saveto
        sett_hbox = HIGHBox()
        sett_hbox._pack_expand_fill(self.setting_saveto_entry)
        sett_hbox._pack_noexpand_nofill(self.setting_saveto_browse)
        sett_table.attach_label(self.setting_saveto, 0, 1, 0, 1)
        sett_table.attach_entry(sett_hbox, 1, 2, 0, 1)

        # mailto, smtp
        sett_hbox = HIGHBox()
        sett_hbox._pack_expand_fill(self.setting_mailto_entry)
        sett_hbox._pack_noexpand_nofill(self.setting_smtp_lbl)
        sett_hbox._pack_expand_fill(self.setting_smtp)
        sett_table.attach_label(self.setting_mailto, 0, 1, 1, 2)
        sett_table.attach_entry(sett_hbox, 1, 2, 1, 2)
        schemasett_hbox._pack_noexpand_nofill(sett_table)

        # add to inventory
        sett_hbox = HIGHBox()
        sett_hbox._pack_noexpand_nofill(self.setting_addtoinv)
        schemasett_hbox._pack_noexpand_nofill(sett_hbox)

        # enabled/disabled
        sett_hbox = HIGHBox()
        sett_hbox._pack_noexpand_nofill(self.setting_enabled)
        schemasett_hbox._pack_noexpand_nofill(sett_hbox)
        settings_align.add(schemasett_hbox)

        self.schema_sett_frame.add(settings_align)

        # bottom buttons
        btns_hbox.set_homogeneous(True)
        btns_hbox._pack_expand_fill(self.help)
        btns_hbox._pack_expand_fill(hig_box_space_holder())
        btns_hbox._pack_expand_fill(self.apply)
        btns_hbox._pack_expand_fill(self.cancel)
        btns_hbox._pack_expand_fill(self.ok)

        main_vbox._pack_noexpand_nofill(header_hbox)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(schema_table)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(self.schema_sett_frame)
        main_vbox.pack_end(btns_hbox, False, False, 0)

        self.add(main_vbox)

    def _exit(self, event):
        """
        Close current and window and profile editor if it is running.
        """
        if self.profile_running:
            self.profile_running._exit(None)

        if self.daddy:
            self.daddy.schemawin = None

        self.destroy()

    def _get_profile_running(self):
        """
        Get profile editor running instance.
        """
        return self.__profilerunning

    def _set_profile_running(self, running):
        """
        Set profile editor instance.
        """
        self.__profilerunning = running

    # Properties
    profile_running = property(_get_profile_running, _set_profile_running)
class SMTPSetup(HIGWindow):
    """
    SMTP editor.
    """
    def __init__(self):
        HIGWindow.__init__(self)

        self.wtitle = _("SMTP Account Editor")

        # header
        self.title_markup = "<span size='16500' weight='heavy'>%s</span>"
        self.ttitle = HIGEntryLabel("")
        self.ttitle.set_line_wrap(False)
        self.ttitle.set_markup(self.title_markup % self.wtitle)
        self.umit_logo = gtk.Image()
        self.umit_logo.set_from_file(logo)
        # schemas name
        self.schema_name_lbl = HIGEntryLabel(_("Schema name"))
        self.schema_name = gtk.combo_box_entry_new_text()
        self.schema_name.connect('changed', self._check_schema)
        # smtp server
        self.smtp_server_lbl = HIGEntryLabel(_("Server"))
        self.smtp_server = gtk.Entry()
        self.smtp_port_lbl = HIGEntryLabel(_("Port"))
        self.smtp_port = gtk.Entry()
        # sending mail..
        self.smtp_mailfrom_lbl = HIGEntryLabel(_("Mail from"))
        self.smtp_mailfrom = gtk.Entry()
        # smtp auth
        self.smtp_need_auth = gtk.CheckButton(
            _("Servers requires authentication"))
        self.smtp_need_auth.connect('toggled', self._auth_need)
        self.smtp_login_lbl = HIGEntryLabel(_("Username"))
        self.smtp_login = gtk.Entry()
        self.smtp_passwd_lbl = HIGEntryLabel(_("Password"))
        self.smtp_passwd = gtk.Entry()
        self.smtp_passwd.set_visibility(False)
        self._auth_need(None)
        # smtp encryption
        self.smtp_encrypt_tls = gtk.CheckButton(_("Use TLS Encryption"))
        """
        Missing: SSL encryption,
                 Other authentication methods.
        """

        # bottom buttons
        self.help = HIGButton(stock=gtk.STOCK_HELP)
        self.help.connect('clicked', self._show_help)
        self.apply = HIGButton(stock=gtk.STOCK_APPLY)
        self.apply.connect('clicked', self._save_schema)
        self.cancel = HIGButton(stock=gtk.STOCK_CANCEL)
        self.cancel.connect('clicked', self._exit)
        self.ok = HIGButton(stock=gtk.STOCK_OK)
        self.ok.connect('clicked', self._save_schema_and_leave)

        self.load_schemas()

        self.__set_props()
        self.__do_layout()

        self.connect('destroy', self._exit)

    def load_schemas(self):
        """
        Load schemas profiles.
        """
        schemas = ConfigParser()
        schemas.read(Path.smtp_schemas)

        self.sections = []
        self.schema_name.get_model().clear()
        for section in schemas.sections():
            self.sections.append(section)
            self.schema_name.append_text(section)

        self.schema_name.set_active(0)
        self._check_schema(None)

    def _load_schema(self):
        """
        Load current set schedule schema.
        """
        schema = ConfigParser()
        schema.read(Path.smtp_schemas)

        enable = {
            'tls': self.smtp_encrypt_tls.set_active,
            'auth': self.smtp_need_auth.set_active
        }
        values = {
            'user': self.smtp_login.set_text,
            'pass': self.smtp_passwd.set_text,
            'server': self.smtp_server.set_text,
            'port': self.smtp_port.set_text,
            'mailfrom': self.smtp_mailfrom.set_text
        }

        for item in schema.items(self.schema_name.get_active_text()):
            if item[0] in ('tls', 'auth'):
                enable[item[0]](int(item[1]))
            else:
                values[item[0]](item[1])

    def _check_schema(self, event):
        """
        Check if current text in schema_name combobox is a schema name.
        """
        if self.schema_name.get_active_text() in self.sections:
            # load schema
            self._load_schema()
        else:
            # reset to default values
            self.smtp_mailfrom.set_text('')
            self.smtp_server.set_text('')
            self.smtp_port.set_text('')
            self.smtp_encrypt_tls.set_active(False)
            self.smtp_login.set_text('')
            self.smtp_passwd.set_text('')
            self.smtp_need_auth.set_active(False)
            self._auth_need(None)

    def _auth_need(self, event):
        """
        SMTP Authentication toggled.
        """
        status = self.smtp_need_auth.get_active()
        self.smtp_login.set_sensitive(status)
        self.smtp_passwd.set_sensitive(status)
        self.smtp_login_lbl.set_sensitive(status)
        self.smtp_passwd_lbl.set_sensitive(status)

    def _save_schema(self, event):
        """
        Save current schema.
        """
        schema = self.schema_name.get_active_text()
        server = self.smtp_server.get_text()
        port = self.smtp_port.get_text()
        auth = self.smtp_need_auth.get_active()
        mailfrom = self.smtp_mailfrom.get_text()

        if auth:
            user = self.smtp_login.get_text()
            passwd = self.smtp_passwd.get_text()

        if auth and not (user and passwd):
            dlg = HIGAlertDialog(self,
                                 message_format=_('SMTP Schema - Error\
 while saving.'),
                                 secondary_text=_("You need to specify an \
username and password for this SMTP Schema."))

            dlg.run()
            dlg.destroy()
            return

        if not schema or not server or not port or not mailfrom:
            dlg = HIGAlertDialog(self,
                                 message_format=_('SMTP Schema - Error\
 while saving.'),
                                 secondary_text=_("The following fields \
need to be filled: Schema Name, Server, Port and Mail from."))

            dlg.run()
            dlg.destroy()
            return

        # write schema to file
        s_cfg = ConfigParser()
        s_cfg.read(Path.smtp_schemas)

        if not s_cfg.has_section(schema):
            new_sec = True
            s_cfg.add_section(schema)
        else:
            new_sec = False

        if auth:
            s_cfg.set(schema, 'auth', '1')
        else:
            s_cfg.set(schema, 'auth', '0')
            user = ''
            passwd = ''

        s_cfg.set(schema, 'port', port)
        s_cfg.set(schema, 'server', server)
        s_cfg.set(schema, 'user', user)
        s_cfg.set(schema, 'pass', passwd)
        s_cfg.set(schema, 'mailfrom', mailfrom)

        if self.smtp_encrypt_tls.get_active():
            s_cfg.set(schema, 'tls', '1')
        else:
            s_cfg.set(schema, 'tls', '0')

        s_cfg.write(open(Path.smtp_schemas, 'w'))

        if new_sec:
            self.load_schemas()

    def _save_schema_and_leave(self, event):
        """
        Save current schema and close editor.
        """
        self._save_schema(None)
        self._exit(None)

    def __set_props(self):
        """
        Set window properties.
        """
        self.set_title(self.wtitle)

    def _show_help(self, event):
        """
        Open SMTP Setup help
        """
        show_help(self, "smtpsetup.html")

    def __do_layout(self):
        """
        Layout widgets in window.
        """
        main_vbox = HIGVBox()
        main_vbox.set_border_width(5)
        main_vbox.set_spacing(12)
        header_hbox = HIGHBox()
        schema_table = HIGTable()
        auth_table = HIGTable()
        btns_hbox = HIGHBox()

        header_hbox._pack_expand_fill(self.ttitle)
        header_hbox._pack_noexpand_nofill(self.umit_logo)

        # schema name
        schema_table.attach_label(self.schema_name_lbl, 0, 1, 0, 1)
        schema_table.attach_entry(self.schema_name, 1, 2, 0, 1)

        # smtp server
        schema_table.attach_label(self.smtp_server_lbl, 0, 1, 1, 2)
        schema_table.attach_entry(self.smtp_server, 1, 2, 1, 2)

        # smtp server port
        schema_table.attach_label(self.smtp_port_lbl, 0, 1, 2, 3)
        schema_table.attach_entry(self.smtp_port, 1, 2, 2, 3)

        # smtp mail from
        schema_table.attach_label(self.smtp_mailfrom_lbl, 0, 1, 3, 4)
        schema_table.attach_entry(self.smtp_mailfrom, 1, 2, 3, 4)

        # smtp user
        auth_table.attach_label(self.smtp_login_lbl, 0, 1, 0, 1)
        auth_table.attach_entry(self.smtp_login, 1, 2, 0, 1)

        # smtp passwd
        auth_table.attach_label(self.smtp_passwd_lbl, 0, 1, 1, 2)
        auth_table.attach_label(self.smtp_passwd, 1, 2, 1, 2)

        # bottom buttons
        btns_hbox.set_homogeneous(True)
        btns_hbox._pack_expand_fill(self.help)
        btns_hbox._pack_expand_fill(hig_box_space_holder())
        btns_hbox._pack_expand_fill(self.apply)
        btns_hbox._pack_expand_fill(self.cancel)
        btns_hbox._pack_expand_fill(self.ok)

        main_vbox._pack_noexpand_nofill(header_hbox)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(schema_table)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(self.smtp_need_auth)
        main_vbox._pack_noexpand_nofill(auth_table)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(self.smtp_encrypt_tls)
        main_vbox.pack_end(btns_hbox, False, False, 0)

        self.add(main_vbox)

    def _exit(self, event):
        """
        Close current window.
        """
        self.destroy()
class HighlightProperty(object):
    def __init__(self, property_name, property):
        self.__create_widgets()

        self.property_name = property_name
        
        self.property_label = property[0].capitalize()
        self.example = property[1]
        self.bold = property[2]
        self.italic = property[3]
        self.underline = property[4]
        
        self.text_color = property[5]
        self.highlight_color = property[6]

        self.__connect_buttons()

    def __create_widgets(self):
        self.property_name_label = HIGEntryLabel("")
        self.example_label = HIGEntryLabel("")
        self.bold_tg_button = HIGToggleButton(" ", gtk.STOCK_BOLD)
        self.italic_tg_button = HIGToggleButton(" ", gtk.STOCK_ITALIC)
        self.underline_tg_button = HIGToggleButton(" ", gtk.STOCK_UNDERLINE)
        self.text_color_button = HIGButton(_("Text"),
                                           stock=gtk.STOCK_SELECT_COLOR)
        self.highlight_color_button = HIGButton(_("Highlight"),
                                                stock=gtk.STOCK_SELECT_COLOR)

    def __connect_buttons(self):
        self.bold_tg_button.connect("toggled", self.update_example)
        self.italic_tg_button.connect("toggled", self.update_example)
        self.underline_tg_button.connect("toggled", self.update_example)

        self.text_color_button.connect("clicked",
                                       self.text_color_dialog)
        self.highlight_color_button.connect("clicked",
                                            self.highlight_color_dialog)


    ####################################
    # Text color dialog
    
    def text_color_dialog(self, widget):
        color_dialog = gtk.ColorSelectionDialog("%s %s" % (self.label,
                                                           _("text color")))
        color_dialog.colorsel.set_current_color(self.text_color)
        
        color_dialog.ok_button.connect("clicked",
                                       self.text_color_dialog_ok,
                                       color_dialog)
        color_dialog.cancel_button.connect("clicked",
                                           self.text_color_dialog_cancel,
                                           color_dialog)
        color_dialog.connect("delete-event",
                             self.text_color_dialog_close,
                             color_dialog)
        
        color_dialog.run()

    def text_color_dialog_ok(self, widget, color_dialog):
        self.text_color = color_dialog.colorsel.get_current_color()
        color_dialog.destroy()
        self.update_example()

    def text_color_dialog_cancel(self, widget, color_dialog):
        color_dialog.destroy()

    def text_color_dialog_close(self, widget, extra, color_dialog):
        color_dialog.destroy()


    #########################################
    # Highlight color dialog
    def highlight_color_dialog(self, widget):
        color_dialog = gtk.ColorSelectionDialog("%s %s" % (self.property_name,
                                                        _("highlight color")))
        color_dialog.colorsel.set_current_color(self.highlight_color)

        color_dialog.ok_button.connect("clicked",
                                       self.highlight_color_dialog_ok,
                                       color_dialog)
        color_dialog.cancel_button.connect("clicked",
                                           self.highlight_color_dialog_cancel,
                                           color_dialog)
        color_dialog.connect("delete-event",
                             self.highlight_color_dialog_close,
                             color_dialog)
        
        color_dialog.run()

    def highlight_color_dialog_ok(self, widget, color_dialog):
        self.highlight_color = color_dialog.colorsel.get_current_color()
        color_dialog.destroy()
        self.update_example()

    def highlight_color_dialog_cancel(self, widget, color_dialog):
        color_dialog.destroy()

    def highlight_color_dialog_close(self, widget, extra, color_dialog):
        color_dialog.destroy()

    def update_example(self, widget=None):
        start = 0
        end = len(self.example)
        
        attributes = pango.AttrList()

        attributes.insert(pango.AttrForeground(self.text_color.red,
                                               self.text_color.green,
                                               self.text_color.blue,
                                               start, end))
        attributes.insert(pango.AttrBackground(self.highlight_color.red,
                                               self.highlight_color.green,
                                               self.highlight_color.blue,
                                               start, end))

        # Bold verification
        if self.bold_tg_button.get_active():
            attributes.insert(pango.AttrWeight(pango.WEIGHT_HEAVY, start, end))
        else:
            attributes.insert(pango.AttrWeight(pango.WEIGHT_NORMAL, start, end))

        # Italic verification
        if self.italic_tg_button.get_active():
            attributes.insert(pango.AttrStyle(pango.STYLE_ITALIC, start, end))
        else:
            attributes.insert(pango.AttrStyle(pango.STYLE_NORMAL, start, end))

        # Underline verification
        if self.underline_tg_button.get_active():
            attributes.insert(pango.AttrUnderline(pango.UNDERLINE_SINGLE,
                                                  start, end))
        else:
            attributes.insert(pango.AttrUnderline(pango.UNDERLINE_NONE,
                                                  start, end))

        self.example_label.set_attributes(attributes)


    def show_bold(self, widget):
        self.example_label.set_markup("<>")

    def get_example(self):
        return self.example_label.get_text()

    def set_example(self, example):
        self.example_label.set_text(example)

    def get_bold(self):
        if self.bold_tg_button.get_active():
            return 1
        return 0

    def set_bold(self, bold):
        self.bold_tg_button.set_active(bold)

    def get_italic(self):
        if self.italic_tg_button.get_active():
            return 1
        return 0

    def set_italic(self, italic):
        self.italic_tg_button.set_active(italic)

    def get_underline(self):
        if self.underline_tg_button.get_active():
            return 1
        return 0

    def set_underline(self, underline):
        self.underline_tg_button.set_active(underline)

    def get_label(self):
        return self.property_name_label.get_text()

    def set_label(self, label):
        self.property_name_label.set_text(label)

    label = property(get_label, set_label)
    example = property(get_example, set_example)
    bold = property(get_bold, set_bold)
    italic = property(get_italic, set_italic)
    underline = property(get_underline, set_underline)
Exemplo n.º 8
0
class NewInventory(HIGWindow):
    """
    A window for creating new or editing existing Inventories.
    """

    def __init__(self, inventory=None, edit_mode=False):
        """
        If you want to load an inventory at startup, pass it to inventory.
        If you want to run this in edit mode, set to True edit_mode.
        """
        HIGWindow.__init__(self)

        self.schemawin = None
        self.discoverywin = None
        self.edit_mode = edit_mode
        if edit_mode:
            self.wtitle = _("Editing Inventory")
        else:
            self.wtitle = _("New Inventory")

        # header
        self.title_markup = "<span size='16500' weight='heavy'>%s</span>"
        self.ttitle = HIGEntryLabel("")
        self.ttitle.set_line_wrap(False)
        self.ttitle.set_markup(self.title_markup % self.wtitle)
        self.umit_logo = gtk.Image()
        self.umit_logo.set_from_file(logo)
        # inventory
        self.invname_lbl = HIGEntryLabel(_("Inventory's name"))
        self.invname = gtk.Entry()
        self.invname.connect('changed', self._check_invname)
        self.invname_inuse = HIGEntryLabel(_("in use"))
        self.invname_inuse.set_sensitive(False)
        self.invenabled = gtk.CheckButton(_("Enabled"))
        self.invenabled.set_active(True)
        # scan command
        self.scandefault = gtk.CheckButton(_("Use default scan options"))
        img_info = gtk.Image()
        img_info.set_from_stock(gtk.STOCK_INFO, gtk.ICON_SIZE_MENU)
        self.scandefault_tip = gtk.EventBox()
        self.scandefault_tip.add(img_info)

        self.scanadv = gtk.Expander(_("Use advanced scan options"))
        self.scan_name_lbl = HIGEntryLabel(_("Scan Profile"))
        self.scan_name = ProfileCombo()
        self.scan_name.update()
        self.scan_name.set_active(0)
        self.scan_name.connect('changed', self._set_scan_command)
        self.cmd_wizard = gtk.Button(stock=gtk.STOCK_CONVERT)
        blbl = self.cmd_wizard.get_children(
            )[0].get_children()[0].get_children()[1]
        blbl.set_text(_("Command Wizard"))
        self.cmd_wizard.connect('clicked', self._open_cmd_wizard)

        self.scan_command_lbl = HIGEntryLabel(_("Command"))
        self.scan_command = gtk.Entry()
        self.scan_command.connect('changed', self._set_scan_type)
        self._set_scan_command(None)
        self.scandefault.set_active(True)
        # scan target
        self.scantarget_lbl = HIGEntryLabel(_("Scan target"))
        self.scantarget = gtk.Entry()
        self.scantarget_discovery = HIGButton(_("Use host discovery"))
        self.scantarget_discovery.connect('clicked', self._open_host_discovery)
        # scheduling profiles
        self.sched_name_lbl = HIGEntryLabel(_("Scheduling Profile"))
        self.sched_name = gtk.combo_box_new_text()
        self.sched_name_edit = gtk.Button(stock=gtk.STOCK_EDIT)
        blbl = self.sched_name_edit.get_children(
            )[0].get_children()[0].get_children()[1]
        blbl.set_text(_("Edit Profiles"))
        self.sched_name_edit.connect('clicked', self._edit_schedprofiles)
        # bottom buttons
        self.help = HIGButton(stock=gtk.STOCK_HELP)
        self.help.connect('clicked', self._show_help)
        self.cancel = HIGButton(stock=gtk.STOCK_CANCEL)
        self.cancel.connect('clicked', self._exit)
        self.ok = HIGButton(stock=gtk.STOCK_OK)
        self.ok.connect('clicked', self._save_inventory_and_leave)

        self.tooltips = gtk.Tooltips()
        self.tooltips.set_tip(self.scandefault_tip,
            _("nmap -T Aggressive -sV -n -O -v target"))

        # disable controls if edit_mode=True
        if edit_mode:
            self.invname.set_sensitive(False)
            self.scandefault.set_sensitive(False)
            self.scandefault_tip.set_sensitive(False)
            self.scanadv.set_sensitive(False)
            self.scan_name.set_sensitive(False)
            self.scan_command.set_sensitive(False)
            self.scantarget_lbl.set_sensitive(False)
            self.scantarget.set_sensitive(False)
            self.scantarget_discovery.set_sensitive(False)

        self.connect('destroy', self._exit)
        self.profile_running = None # no SchedProfileEditor instance is running.
        self.load_schemas()
        self._load_pscheds()

        # load an inventory if especified
        self.loaded_command = None
        if inventory:
            self.load_inventory(inventory)

        self.__set_props()
        self.__do_layout()


    def load_inventory(self, inventory):
        """
        Load inventory.
        """
        inv = ConfigParser()
        inv.read(Path.sched_schemas)

        if not inv.has_section(inventory):
            dlg = NoScheduleDlg()
            dlg.run()
            dlg.destroy()
            raise NoInventory(inventory)

        self.invname.set_text(inventory)
        for item in inv.items(inventory):
            if item[0] == 'profile':
                pindx = self.profiles.index(item[1])
                self.sched_name.set_active(pindx)
            if item[0] == 'enabled':
                self.invenabled.set_active(int(item[1]))
            if item[0] == 'command':
                self.loaded_command = item[1]


    def load_schemas(self):
        """
        Load scheduler schemas profiles.
        """
        schemas = ConfigParser()
        schemas.read(Path.sched_schemas)

        self.sections = [ ]
        for section in schemas.sections():
            self.sections.append(section)


    def _load_pscheds(self):
        """
        Load scheduling profiles.
        """
        pscheds = ConfigParser()
        pscheds.read(Path.sched_profiles)

        self.profiles = [ ]
        self.sched_name.get_model().clear()
        for section in pscheds.sections():
            self.sched_name.append_text(section)
            self.profiles.append(section)

        self.sched_name.set_active(0)


    def _check_invname(self, event):
        """
        Check if Inventory's name isn't in use.
        """
        if self.invname.get_text() and \
           (self.invname.get_text() in self.sections) and \
            not self.edit_mode:
            self.invname_inuse.set_sensitive(True)
        else:
            self.invname_inuse.set_sensitive(False)


    def _edit_schedprofiles(self, event):
        """
        Open Scheduling Profiles Editor.
        """
        if self.profile_running:
            return

        win = SchedProfileEditor(self, self.sched_name.get_active_text())
        win.show_all()
        self.profile_running = win


    def _set_scan_type(self, event):
        """
        When scan command is changed, unset "Default scan options" if it is
        selected.
        """
        if self.scandefault.get_active():
            self.scandefault.set_active(False)


    def _open_cmd_wizard(self, event):
        """
        Run command wizard window and update combobox when it finishes.
        """
        def update_scan_profiles(wwin):
            self.scan_name.update()

        w = Wizard()
        w.show_all()
        w.connect('destroy', update_scan_profiles)


    def _open_host_discovery(self, event):
        """
        Open host discovery window.
        """
        if self.discoverywin:
            return

        w = HostDiscovery(self)
        w.show_all()

        self.discoverywin = w


    def get_discoverywin(self):
        """
        Get HostDiscovery running instance.
        """
        return self.__discoverywin


    def set_discoverywin(self, win):
        """
        Set HostDiscovery instance.
        """
        self.__discoverywin = win


    def get_schemawin(self):
        """
        Get scheduelr schemas editor running instance.
        """
        return self.__schemawin


    def set_schemawin(self, win):
        """
        Set scheduler schemas editor instance.
        """
        self.__schemawin = win


    def get_profile_running(self):
        """
        Get profile editor running instance.
        """
        return self.__profilerunning


    def set_profile_running(self, running):
        """
        Set profile editor instance.
        """
        self.__profilerunning = running


    def _save_inventory(self, event):
        """
        Save inventory.
        """
        target = self.scantarget.get_text()
        invname = self.invname.get_text()
        notinuse = (self.invname_inuse.state == gtk.STATE_INSENSITIVE)
        command_adv = self.scan_command.get_text()
        
        # checking for errors
        if not notinuse or not len(invname) and not self.edit_mode:
            dlg = HIGAlertDialog(self,
                message_format=_("New Inventory - Error while creating."),
                secondary_text=_("You tried to use an existing Inventory "
                    "name or you didn't specify one."))

            dlg.run()
            dlg.destroy()
            return 0

        if not len(target) and not self.edit_mode:
            dlg = HIGAlertDialog(self,
                message_format=_("New Inventory - Error  while creating."),
                    secondary_text=_("You didn't specify any target."))

            dlg.run()
            dlg.destroy()
            return 0
            
       
        if not self.edit_mode:
        	if Address_Checker(target) == "IPV4" :
        		option = ""
        	elif Address_Checker(target) == "IPV6":
        		option = "-6 "
        	elif Address_Checker(target) == "MAC":
        		option = ""
        	else:
        		option = ""
        		dlg = HIGAlertDialog(self,
        			message_format=_("New Inentory - Error While Creating."),
        			secondary_text=_("You need to enter correct address either"
        				"IPV4 or IPv6 or MAC address"))
        		dlg.run()
        		dlg.destroy()
        		return 0


        if not len(command_adv) and not self.scandefault.get_active() \
            and not self.edit_mode:
            dlg = HIGAlertDialog(self,
                message_format=_("New Inventory - Error while creating."),
                secondary_text=_("You need to toggle \"Use default scan "
                    "options\" or specify a command."))

            dlg.run()
            dlg.destroy()
            return 0
        # end error checking

        if self.scandefault.get_active() and not self.edit_mode:
            command = "nmap -T Aggressive -sV -n -O -v " + option +target
        elif not self.edit_mode:
            target_cmd = "<target>"
            target_pos = command_adv.find(target_cmd)
            if target_pos != -1:
                start = target_pos
                end = target_pos + len(target_cmd)
                command = command_adv[:start] + option +target + command_adv[end:]
            else:
                dlg = HIGAlertDialog(self,
                    message_format=_("New Inventory - Error while creating."),
                    secondary_text=_("It seems you removed <target> from the "
                        "Scan command entry, you need to leave it somewhere "
                        "there."))

                dlg.run()
                dlg.destroy()
                return 0

        schedule = self.sched_name.get_active_text()
        enabled = int(self.invenabled.get_active())
        # write inventory to schema's file
        s_cfg = ConfigParser()
        s_cfg.read(Path.sched_schemas)

        if not s_cfg.has_section(invname):
            new_sec = True
            s_cfg.add_section(invname)
        elif self.edit_mode:
            new_sec = False
        else:
            print "How the hell did we get here?!"
            print "Report as BUG"
            return 0

        if new_sec:
            # New Section
            s_cfg.set(invname, 'profile', schedule)
            s_cfg.set(invname, 'command', command)
            s_cfg.set(invname, 'enabled', enabled)
            s_cfg.set(invname, 'addtoinv', '2')
            s_cfg.set(invname, 'saveto', '')
            s_cfg.set(invname, 'mailto', '')
            s_cfg.set(invname, 'smtp', '')
        else:
            # Edit Mode
            s_cfg.set(invname, 'profile', schedule)
            s_cfg.set(invname, 'enabled', enabled)
            #here i have to put check for scan target field
            command_text = self.cmd_entry.get_text()
            if command_text.find("nmap") == -1:
            	dlg = HIGAlertDialog(self,
            		message_format=_("Edit Inventory - Error while creating."),
            		secondary_text=_("It seems you have not entered namp in "
            			"command field. enter correct command with target."))
            	dlg.run()
            	dlg.destroy()
            	return 0
            	
            s_cfg.set(invname, 'command', command_text)

        s_cfg.write(open(Path.sched_schemas, 'w'))

        self.load_schemas()

        return 1


    def _save_inventory_and_leave(self, event):
        """
        Save Inventory and close window.
        """
        close_win = self._save_inventory(None)
        if close_win:
            self._exit(None)


    def _set_scan_command(self, event):
        """
        Set scan command based on chosen profile.
        """
        profile = self.scan_name.get_selected_profile()
        cmd_profile = CommandProfile()
        command = cmd_profile.get_command(profile)
        self.scan_command.set_text(command % '<target>')


    def _show_help(self, event):
        """
        Show help for creating a New Inventory.
        """
        pass


    def _exit(self, event):
        """
        Close window.
        """
        if self.schemawin:
            self.schemawin._exit(None)

        if self.profile_running:
            self.profile_running._exit(None)

        self.destroy()


    def __set_props(self):
        """
        Set window properties.
        """
        self.set_title(self.wtitle)


    def __do_layout(self):
        """
        Layout widgets.
        """
        main_vbox = HIGVBox()
        main_vbox.set_border_width(5)
        main_vbox.set_spacing(12)
        header_hbox = HIGHBox()
        invname_hbox = HIGHBox()
        scan_hbox = HIGHBox()
        scanadv_hbox = HIGHBox()
        scantarget_hbox = HIGHBox()
        sched_box = HIGHBox()
        btns_hbox = HIGHBox()

        # header
        header_hbox._pack_expand_fill(self.ttitle)
        header_hbox._pack_noexpand_nofill(self.umit_logo)
        # inventory's name
        invname_hbox._pack_noexpand_nofill(self.invname_lbl)
        invname_hbox._pack_expand_fill(self.invname)
        invname_hbox._pack_noexpand_nofill(self.invname_inuse)
        invname_hbox._pack_noexpand_nofill(self.invenabled)
        # scan command
        scan_hbox._pack_noexpand_nofill(self.scandefault)
        scan_hbox._pack_noexpand_nofill(self.scandefault_tip)
        scanadv_hbox._pack_expand_fill(self.scanadv)

        adv_box = HIGVBox()
        scanadv_align = gtk.Alignment(0.5, 0.5, 1, 1)
        scanadv_align.set_padding(6, 0, 12, 0)
        scanname_box = HIGHBox()
        scanname_box._pack_noexpand_nofill(self.scan_name_lbl)
        scanname_box._pack_expand_fill(self.scan_name)
        scanname_box._pack_noexpand_nofill(self.cmd_wizard)
        adv_box.add(scanname_box)
        scancmd_box = HIGHBox()
        scancmd_box._pack_noexpand_nofill(self.scan_command_lbl)
        scancmd_box._pack_expand_fill(self.scan_command)
        adv_box.add(scancmd_box)

        scanadv_align.add(adv_box)
        self.scanadv.add(scanadv_align)
        # scan target
        scantarget_hbox._pack_noexpand_nofill(self.scantarget_lbl)
        scantarget_hbox._pack_expand_fill(self.scantarget)
        scantarget_hbox._pack_noexpand_nofill(self.scantarget_discovery)
        # scheduling profiles
        sched_box._pack_noexpand_nofill(self.sched_name_lbl)
        sched_box._pack_expand_fill(self.sched_name)
        sched_box._pack_noexpand_nofill(self.sched_name_edit)
        # bottom buttons
        btns_hbox.set_homogeneous(True)
        btns_hbox._pack_expand_fill(self.help)
        btns_hbox._pack_expand_fill(hig_box_space_holder())
        btns_hbox._pack_expand_fill(self.cancel)
        btns_hbox._pack_expand_fill(self.ok)


        main_vbox._pack_noexpand_nofill(header_hbox)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(invname_hbox)
        main_vbox._pack_noexpand_nofill(scan_hbox)
        main_vbox._pack_noexpand_nofill(scanadv_hbox)
        main_vbox._pack_noexpand_nofill(scantarget_hbox)
        
        if self.loaded_command and self.edit_mode:
            view_cmd_box = HIGHBox()
            view_cmd_box._pack_noexpand_nofill(gtk.Label(_("Command")))
            # XXX Why don't reuse scan_command?
            self.cmd_entry = gtk.Entry()
            self.cmd_entry.set_text(self.loaded_command)
            view_cmd_box._pack_expand_fill(self.cmd_entry)
            img_info = gtk.Image()
            img_info.set_from_stock(gtk.STOCK_INFO, gtk.ICON_SIZE_MENU)
            eb = gtk.EventBox()
            eb.add(img_info)
            self.tooltips.set_tip(eb, _("Changes in command won't be saved!"))
            view_cmd_box.pack_end(eb, False, False, 0)
            main_vbox._pack_noexpand_nofill(view_cmd_box)

        main_vbox._pack_noexpand_nofill(sched_box)
        main_vbox.pack_end(btns_hbox, False, False, 0)
        main_vbox.pack_end(gtk.HSeparator(), False, False, 0)

        self.add(main_vbox)


    # Properties
    schemawin = property(get_schemawin, set_schemawin)
    discoverywin = property(get_discoverywin, set_discoverywin)
    profile_running = property(get_profile_running, set_profile_running)
class SchedProfileEditor(HIGWindow):
    """
    Scheduling Profiles Editor
    """
    def __init__(self, daddy, profile=None):
        HIGWindow.__init__(self)
        self.daddy = daddy

        self.wtitle = _("Scheduling Profiles Editor")
        self.start_profile = profile

        # header
        self.title_markup = "<span size='16500' weight='heavy'>%s</span>"
        self.ttitle = HIGEntryLabel("")
        self.ttitle.set_line_wrap(False)
        self.ttitle.set_markup(self.title_markup % self.wtitle)
        self.umit_logo = gtk.Image()
        self.umit_logo.set_from_file(logo)
        # profiles name
        self.schedp_name_lbl = HIGEntryLabel(_("Scheduling Profile"))
        self.schedp_name = gtk.combo_box_entry_new_text()
        self.schedp_name.connect('changed', self._check_profile)
        # cron format
        self.cron_frame = HIGFrame(_("Schedule"))
        self.cron_minute_lbl = HIGEntryLabel(_("Minute"))
        self.cron_minute = gtk.Entry()
        self.cron_hour_lbl = HIGEntryLabel(_("Hour"))
        self.cron_hour = gtk.Entry()
        self.cron_day_lbl = HIGEntryLabel(_("Day of month"))
        self.cron_day = gtk.Entry()
        self.cron_month_lbl = HIGEntryLabel(_("Month"))
        self.cron_month = gtk.Entry()
        self.cron_weekday_lbl = HIGEntryLabel(_("Weekday"))
        self.cron_weekday = gtk.Entry()
        # bottom buttons
        self.help = HIGButton(stock=gtk.STOCK_HELP)
        self.help.connect('clicked', self._show_help)
        self.apply = HIGButton(stock=gtk.STOCK_APPLY)
        self.apply.connect('clicked', self._save_profile)
        self.cancel = HIGButton(stock=gtk.STOCK_CANCEL)
        self.cancel.connect('clicked', self._exit)
        self.ok = HIGButton(stock=gtk.STOCK_OK)
        self.ok.connect('clicked', self._save_profile_and_leave)

        self.load_profiles()
        self.__set_props()
        self.__do_layout()

        self.connect('destroy', self._exit)

    def load_profiles(self):
        """
        Load scheduling profiles.
        """
        profiles = ConfigParser()
        profiles.read(Path.sched_profiles)

        self.sections = []
        ind = 0
        for indx, section in enumerate(profiles.sections()):
            self.sections.append(section)
            self.schedp_name.append_text(section)
            if section == self.start_profile:
                ind = indx

        self.schedp_name.set_active(ind)

        self._check_profile(None)

    def _load_profile(self):
        """
        Load current set schedule profile.
        """
        profile = ConfigParser()
        profile.read(Path.sched_profiles)

        values = {
            'minute': self.cron_minute.set_text,
            'hour': self.cron_hour.set_text,
            'day': self.cron_day.set_text,
            'month': self.cron_month.set_text,
            'weekday': self.cron_weekday.set_text
        }

        for item in profile.items(self.schedp_name.get_active_text()):
            values[item[0]](item[1])

    def _check_profile(self, event):
        """
        Check if current text in schedp_name combobox is a profile name.
        """
        if self.schedp_name.get_active_text() in self.sections:
            self._load_profile()
        else:
            self.cron_minute.set_text('')
            self.cron_hour.set_text('')
            self.cron_day.set_text('')
            self.cron_month.set_text('')
            self.cron_weekday.set_text('')

    def _save_profile(self, event):
        """
        Save scheduling profile.
        """
        pname = self.schedp_name.get_active_text()
        if not len(pname):
            dlg = HIGAlertDialog(self,
                                 message_format=_('Scheduling Profile - Error \
while saving'),
                                 secondary_text=_("You need to specify a name \
for Profile."))
            dlg.run()
            dlg.destroy()
            return

        parser = CronParser()
        minute = self.cron_minute.get_text()
        hour = self.cron_hour.get_text()
        day = self.cron_day.get_text()
        month = self.cron_month.get_text()
        weekday = self.cron_weekday.get_text()
        try:
            parser.parse_minute(minute)
            parser.parse_hour(hour)
            parser.parse_day(day)
            parser.parse_month(month)
            parser.parse_weekday(weekday)
        except Exception, e:
            dlg = HIGAlertDialog(self,
                                 message_format=_('Scheduling Profile - Error \
while saving'),
                                 secondary_text=_("Check your cron syntax and \
try to save again."))
            dlg.run()
            dlg.destroy()
            return

        # write profile to file
        p_cfg = ConfigParser()
        p_cfg.read(Path.sched_profiles)

        if not p_cfg.has_section(pname):
            new_sec = True
            p_cfg.add_section(pname)
        else:
            new_sec = False

        p_cfg.set(pname, 'minute', minute)
        p_cfg.set(pname, 'hour', hour)
        p_cfg.set(pname, 'day', day)
        p_cfg.set(pname, 'month', month)
        p_cfg.set(pname, 'weekday', weekday)

        p_cfg.write(open(Path.sched_profiles, 'w'))

        if new_sec:  # update daddy scheduling profiles list
            self.daddy._load_pscheds()
class SchedSchemaEditor(HIGWindow):
    """
    Scheduler Schemas Editor
    """
    def __init__(self, daddy=None):
        HIGWindow.__init__(self)

        self.daddy = daddy
        self.wtitle = _("Scan Scheduler Editor")

        # header
        self.title_markup = "<span size='16500' weight='heavy'>%s</span>"
        self.ttitle = HIGEntryLabel("")
        self.ttitle.set_line_wrap(False)
        self.ttitle.set_markup(self.title_markup % self.wtitle)
        self.umit_logo = gtk.Image()
        self.umit_logo.set_from_file(logo)
        # schemas name
        self.schema_name_lbl = HIGEntryLabel(_("Schema Name"))
        self.schema_name = gtk.combo_box_entry_new_text()
        self.schema_name.connect('changed', self._check_schema)
        # target and scan profiles
        #self.target_lbl = HIGEntryLabel(_("Target"))
        #self.target = gtk.Entry()
        self.scan_name_lbl = HIGEntryLabel(_("Scan Profile"))
        self.scan_name = ProfileCombo()
        self.scan_name.update()
        self.scan_name.set_active(0)
        self.scan_name.connect('changed', self._set_scan_command)
        # scan command
        self.scan_command_lbl = HIGEntryLabel(_("Command"))
        self.scan_command = gtk.Entry()
        # scheduling profile
        self.sched_name_lbl = HIGEntryLabel(_("Scheduling Profile"))
        self.sched_name = gtk.combo_box_new_text()
        self.sched_name_edit = gtk.Button(stock=gtk.STOCK_EDIT)
        blbl = self.sched_name_edit.get_children()[0].get_children(
        )[0].get_children()[1]
        blbl.set_text(_("Edit Profiles"))
        self.sched_name_edit.connect('clicked', self._edit_schedprofiles)
        # schema settings
        self.schema_sett_frame = HIGFrame()
        self.setting_saveto = gtk.CheckButton(_("Save outputs to"))
        self.setting_saveto_entry = gtk.Entry()
        self.setting_saveto_browse = gtk.Button(_("..."))
        self.setting_saveto_browse.connect('clicked', self._select_saveto)
        self.setting_mailto = gtk.CheckButton(_("Send output to email"))
        self.setting_mailto_entry = gtk.Entry()
        self.setting_smtp_lbl = HIGEntryLabel(_("SMTP Schema"))
        self.setting_smtp = gtk.combo_box_new_text()
        self.setting_addtoinv = gtk.CheckButton(_("Add to the Inventory"))
        self.setting_enabled = gtk.CheckButton(_("Enabled"))
        # bottom buttons
        self.help = HIGButton(stock=gtk.STOCK_HELP)
        self.help.connect('clicked', self._show_help)
        self.apply = HIGButton(stock=gtk.STOCK_APPLY)
        self.apply.connect('clicked', self._save_schema)
        self.cancel = HIGButton(stock=gtk.STOCK_CANCEL)
        self.cancel.connect('clicked', self._exit)
        self.ok = HIGButton(stock=gtk.STOCK_OK)
        self.ok.connect('clicked', self._save_schema_and_leave)

        self.load_smtp_schemas()
        self._set_scan_command(None)
        self.profile_running = None  # no SchedProfileEditor instance is running.
        self._load_pscheds()
        self.load_schemas()

        self.__set_props()
        self.__do_layout()

        self.connect('destroy', self._exit)

    def load_smtp_schemas(self):
        """
        Load smtp profiles.
        """
        schemas = ConfigParser()
        schemas.read(Path.smtp_schemas)

        self.smtp_sections = []
        self.setting_smtp.get_model().clear()
        for section in schemas.sections():
            self.smtp_sections.append(section)
            self.setting_smtp.append_text(section)

        self.setting_smtp.set_active(0)

    def load_schemas(self):
        """
        Load schemas profiles.
        """
        schemas = ConfigParser()
        schemas.read(Path.sched_schemas)

        self.sections = []
        self.schema_name.get_model().clear()
        for section in schemas.sections():
            self.sections.append(section)
            self.schema_name.append_text(section)

        self.schema_name.set_active(0)
        self._check_schema(None)

    def _load_schema(self):
        """
        Load current set schedule schema.
        """
        schema = ConfigParser()
        schema.read(Path.sched_schemas)

        values = {
            'command': self.scan_command.set_text,
            'saveto': self.setting_saveto_entry.set_text,
            'mailto': self.setting_mailto_entry.set_text
        }
        enable = {
            'saveto': self.setting_saveto.set_active,
            'mailto': self.setting_mailto.set_active
        }

        for item in schema.items(self.schema_name.get_active_text()):
            if item[0] == 'addtoinv':
                self.setting_addtoinv.set_active(int(item[1]))
                if item[1] == '2':
                    self.apply.set_sensitive(False)
                    self.ok.set_sensitive(False)
                else:
                    self.apply.set_sensitive(True)
                    self.ok.set_sensitive(True)
            elif item[0] == 'enabled':
                self.setting_enabled.set_active(int(item[1]))
            elif item[0] == 'profile':
                pindx = self.profiles.index(item[1])
                self.sched_name.set_active(pindx)
            elif item[0] == 'smtp':
                if item[1]:
                    pindx = self.smtp_sections.index(item[1])
                    self.setting_smtp.set_active(pindx)
            else:
                values[item[0]](item[1])
                if item[0] in ('saveto', 'mailto'):
                    if len(item[1]):
                        enable[item[0]](True)
                    else:
                        enable[item[0]](False)

    def _check_schema(self, event):
        """
        Check if current text in schema_name combobox is a schema name.
        """
        if self.schema_name.get_active_text() in self.sections:
            # load schema
            self._load_schema()
        else:
            # reset to default values
            self.apply.set_sensitive(True)
            self.ok.set_sensitive(True)
            self.setting_addtoinv.set_active(False)
            self.setting_enabled.set_active(False)
            self.setting_mailto.set_active(False)
            self.setting_mailto_entry.set_text('')
            self.setting_saveto.set_active(False)
            self.setting_saveto_entry.set_text('')

        self.schema_sett_frame._set_label(self.schema_name.get_active_text() \
+ " - Settings")

    def _set_scan_command(self, event):
        """
        Set scan command based on chosen profile.
        """
        profile = self.scan_name.get_selected_profile()
        cmd_profile = CommandProfile()
        command = cmd_profile.get_command(profile)
        self.scan_command.set_text(command % '<target>')

    def _load_pscheds(self):
        """
        Load scheduling profiles.
        """
        pscheds = ConfigParser()
        pscheds.read(Path.sched_profiles)

        self.profiles = []
        self.sched_name.get_model().clear()
        for section in pscheds.sections():
            self.sched_name.append_text(section)
            self.profiles.append(section)

        self.sched_name.set_active(0)

    def _edit_schedprofiles(self, event):
        """
        Open Scheduling Profiles Editor.
        """
        if self.profile_running:
            return

        win = SchedProfileEditor(self, self.sched_name.get_active_text())
        win.show_all()
        self.profile_running = win

    def _select_saveto(self, event):
        """
        Select directory to save file.
        """
        dir_chooser = DirectoryChooserDialog(_("Select a directory"))

        dir_chooser.run()
        dir_chosen = dir_chooser.get_filename()
        dir_chooser.destroy()
        self.setting_saveto_entry.set_text(dir_chosen)

    def _save_schema(self, event):
        """
        Save current schema.
        """
        schema = self.schema_name.get_active_text()
        command = self.scan_command.get_text()
        schedule = self.sched_name.get_active_text()
        mailto = self.setting_mailto.get_active()

        if not schema or not schedule or not command or '<target>' in command:
            dlg = HIGAlertDialog(self,
                                 message_format=_('Scheduling Schema - Error\
 while saving.'),
                                 secondary_text=_("There is some error in at \
least one of the following fields: \"Schema name\", \"Command\" or \"Scheduling\
 Profile\"\n\nCheck if \"Schema name\" is not empty.\nCheck if \"Command\" does\
 contain \"<target>\" on it.\nCheck if there is some \"Scheduling Profile\" \
selected."))

            dlg.run()
            dlg.destroy()
            return

        if mailto and not self.setting_smtp.get_active_text():
            dlg = HIGAlertDialog(self,
                                 message_format=_('Scheduling Schema - Error\
 while saving.'),
                                 secondary_text=_("You need to create a \
a SMTP Schema for sending email."))

            dlg.run()
            dlg.destroy()
            return

        # check for output existance
        if self.setting_saveto.get_active() and \
           not os.path.isdir(self.setting_saveto_entry.get_text()):

            dlg = HIGAlertDialog(self,
                                 message_format=_('Scheduling Schema - Error\
 while saving.'),
                                 secondary_text=_("You especified an invalid \
directory to save scans output."))

            dlg.run()
            dlg.destroy()
            return

        # write schema to file
        s_cfg = ConfigParser()
        s_cfg.read(Path.sched_schemas)

        if not s_cfg.has_section(schema):
            new_sec = True
            s_cfg.add_section(schema)
        else:
            new_sec = False

        s_cfg.set(schema, 'profile', schedule)
        s_cfg.set(schema, 'command', command)
        if self.setting_enabled.get_active():
            s_cfg.set(schema, 'enabled', '1')
        else:
            s_cfg.set(schema, 'enabled', '0')
        if self.setting_addtoinv.get_active():
            s_cfg.set(schema, 'addtoinv', '1')
        else:
            s_cfg.set(schema, 'addtoinv', '0')
        if self.setting_saveto.get_active():
            s_cfg.set(schema, 'saveto', self.setting_saveto_entry.get_text())
        else:
            s_cfg.set(schema, 'saveto', '')
        if mailto:
            s_cfg.set(schema, 'mailto', self.setting_mailto_entry.get_text())
            s_cfg.set(schema, 'smtp', self.setting_smtp.get_active_text())
        else:
            s_cfg.set(schema, 'mailto', '')
            s_cfg.set(schema, 'smtp', '')

        s_cfg.write(open(Path.sched_schemas, 'w'))

        if new_sec:
            self.load_schemas()

        if self.daddy:
            self.daddy.load_schemas()

    def _save_schema_and_leave(self, event):
        """
        Save current schema and close editor.
        """
        self._save_schema(None)
        self._exit(None)

    def _show_help(self, event):
        """
        Show help for Scan Scheduler Editor.
        """
        show_help(self, "scheduler.html#setting-up-a-schedule")

    def __set_props(self):
        """
        Set window properties.
        """
        self.set_title(self.wtitle)
        self.set_default_size(440, -1)

    def __do_layout(self):
        """
        Layout widgets in window.
        """
        main_vbox = HIGVBox()
        main_vbox.set_border_width(5)
        main_vbox.set_spacing(12)
        header_hbox = HIGHBox()
        schema_table = HIGTable()
        schedsn_hbox = HIGHBox()
        sett_table = HIGTable()
        btns_hbox = HIGHBox()

        header_hbox._pack_expand_fill(self.ttitle)
        header_hbox._pack_noexpand_nofill(self.umit_logo)

        # schema name
        schema_table.attach_label(self.schema_name_lbl, 0, 1, 0, 1)
        schema_table.attach_entry(self.schema_name, 1, 2, 0, 1)

        # target and scan profile
        schema_table.attach_label(self.scan_name_lbl, 0, 1, 1, 2)
        schema_table.attach_entry(self.scan_name, 1, 2, 1, 2)

        # scan command
        schema_table.attach_label(self.scan_command_lbl, 0, 1, 2, 3)
        schema_table.attach_label(self.scan_command, 1, 2, 2, 3)

        # scheduling profile
        schedsn_hbox._pack_expand_fill(self.sched_name)
        schedsn_hbox._pack_noexpand_nofill(self.sched_name_edit)

        schema_table.attach_label(self.sched_name_lbl, 0, 1, 3, 4)
        schema_table.attach_entry(schedsn_hbox, 1, 2, 3, 4)

        # settings frame
        settings_align = gtk.Alignment(0.5, 0.5, 1, 1)
        settings_align.set_padding(6, 0, 12, 0)
        schemasett_hbox = HIGVBox()

        # saveto
        sett_hbox = HIGHBox()
        sett_hbox._pack_expand_fill(self.setting_saveto_entry)
        sett_hbox._pack_noexpand_nofill(self.setting_saveto_browse)
        sett_table.attach_label(self.setting_saveto, 0, 1, 0, 1)
        sett_table.attach_entry(sett_hbox, 1, 2, 0, 1)

        # mailto, smtp
        sett_hbox = HIGHBox()
        sett_hbox._pack_expand_fill(self.setting_mailto_entry)
        sett_hbox._pack_noexpand_nofill(self.setting_smtp_lbl)
        sett_hbox._pack_expand_fill(self.setting_smtp)
        sett_table.attach_label(self.setting_mailto, 0, 1, 1, 2)
        sett_table.attach_entry(sett_hbox, 1, 2, 1, 2)
        schemasett_hbox._pack_noexpand_nofill(sett_table)

        # add to inventory
        sett_hbox = HIGHBox()
        sett_hbox._pack_noexpand_nofill(self.setting_addtoinv)
        schemasett_hbox._pack_noexpand_nofill(sett_hbox)

        # enabled/disabled
        sett_hbox = HIGHBox()
        sett_hbox._pack_noexpand_nofill(self.setting_enabled)
        schemasett_hbox._pack_noexpand_nofill(sett_hbox)
        settings_align.add(schemasett_hbox)

        self.schema_sett_frame.add(settings_align)

        # bottom buttons
        btns_hbox.set_homogeneous(True)
        btns_hbox._pack_expand_fill(self.help)
        btns_hbox._pack_expand_fill(hig_box_space_holder())
        btns_hbox._pack_expand_fill(self.apply)
        btns_hbox._pack_expand_fill(self.cancel)
        btns_hbox._pack_expand_fill(self.ok)

        main_vbox._pack_noexpand_nofill(header_hbox)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(schema_table)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_noexpand_nofill(self.schema_sett_frame)
        main_vbox.pack_end(btns_hbox, False, False, 0)

        self.add(main_vbox)

    def _exit(self, event):
        """
        Close current and window and profile editor if it is running.
        """
        if self.profile_running:
            self.profile_running._exit(None)

        if self.daddy:
            self.daddy.schemawin = None

        self.destroy()

    def _get_profile_running(self):
        """
        Get profile editor running instance.
        """
        return self.__profilerunning

    def _set_profile_running(self, running):
        """
        Set profile editor instance.
        """
        self.__profilerunning = running

    # Properties
    profile_running = property(_get_profile_running, _set_profile_running)
class HostDiscovery(gtk.Window):
    """
    GUI for network/host discovery.
    """
    def __init__(self, daddy):
        gtk.Window.__init__(self)

        self.daddy = daddy
        self.rowsel = None
        self.tooltips = gtk.Tooltips()
        self.wtitle = _("Host Discovery")

        # header
        self.title_markup = "<span size='16500' weight='heavy'>%s</span>"
        self.ttitle = HIGEntryLabel("")
        self.ttitle.set_line_wrap(False)
        self.ttitle.set_markup(self.title_markup % self.wtitle)
        self.umit_logo = gtk.Image()
        self.umit_logo.set_from_file(logo)
        # discovery options
        self.netdetect_btn = gtk.Button(_("Detect network(s)"))
        self.netdetect_btn.connect('clicked', self.get_networks)
        self.networks_box = None
        self.addnetworks = gtk.Button(_("Add new entry"))
        self.addnetworks.connect('clicked', self._create_network_entry)
        self.hostdetect_btn = gtk.Button(_("Find hosts"))
        self.hostdetect_btn.connect('clicked', self.get_addresses)
        # target list
        self.target_lbl = HIGEntryLabel(_("Target list"))
        self.target_model = gtk.ListStore(gobject.TYPE_STRING,
                                          gobject.TYPE_STRING)
        self.tview = gtk.TreeView(self.target_model)
        self.tview.set_size_request(300, int(300 / 1.6))
        self.tview.columns = [None] * 2
        self.tview.columns[0] = gtk.TreeViewColumn(_("Host"))
        self.tview.columns[1] = gtk.TreeViewColumn(_("Network"))
        for n in range(2):
            self.tview.append_column(self.tview.columns[n])
            self.tview.columns[n].cell = gtk.CellRendererText()
            self.tview.columns[n].pack_start(self.tview.columns[n].cell, True)
            self.tview.columns[n].set_attributes(self.tview.columns[n].cell,
                                                 text=n)
        self.tview.get_selection().connect('changed', self._tview_sel_change)
        self.target_remove = gtk.Button(_("Remove from list"))
        self.target_remove.set_sensitive(False)
        self.target_remove.connect('clicked', self._remove_target)
        # bottom buttons
        self.help = HIGButton(stock=gtk.STOCK_HELP)
        self.help.connect('clicked', self._show_help)
        self.cancel = HIGButton(stock=gtk.STOCK_CANCEL)
        self.cancel.connect('clicked', self._exit)
        self.apply = HIGButton(stock=gtk.STOCK_APPLY)
        self.apply.connect('clicked', self._return_list)

        # tooltips
        self.tooltips.set_tip(self.addnetworks,
                              _("Add new entry for a network"))
        self.tooltips.set_tip(self.netdetect_btn,
                              _("Try to detect network(s)"))
        self.tooltips.set_tip(self.hostdetect_btn,
                              _("Find hosts in entered network(s)"))
        self.tooltips.set_tip(self.target_remove,
                              _("Remove selection from target list"))

        self.__layout()

    def _create_network_entry(self, event):
        """
        Create a new network entry.
        """
        entry = gtk.Entry()
        entry.set_text('')
        entry.show()
        self.networks_box.add(entry)

    def _tview_sel_change(self, event):
        """
        Row selection changed in treeview.
        """
        model, tv_iter = event.get_selected()
        self.rowsel = tv_iter
        self.target_remove.set_sensitive(True)

    def _remove_target(self, event):
        """
        Remove a host from target list.
        """
        if self.rowsel:
            self.target_model.remove(self.rowsel)
            self.target_remove.set_sensitive(False)
            self.rowsel = None

    def _show_help(self, event):
        """
        Show help.
        """
        pass

    def _exit(self, event):
        """
        Close window.
        """
        self.daddy.discoverywin = None  # daddy is NewInventory instance
        self.destroy()

    def _return_list(self, event):
        """
        Return target list.
        """
        hosts = []
        for row in self.target_model:
            hosts.append(row[0])

        self.results = ' '.join([str(h) for h in hosts])

        if self.daddy:  # NewInventory instance
            self.daddy.scantarget.set_text(self.results)

        self._exit(None)

    def get_networks(self, event):
        """
        Try to detect network(s).
        """
        networks = tryto_detect_networks()

        if not networks:
            dlg = HIGAlertDialog(
                self,
                message_format=_("No network(s) detected."),
                secondary_text=_(
                    "You will need to especify the "
                    "network(s) yourself before detecting hosts."))
            dlg.run()
            dlg.destroy()
            return

        entries = len(self.networks_box.get_children()) - 1

        for amount, nw in enumerate(networks):
            if amount == entries:
                e = gtk.Entry()
                e.set_text('')
                e.show()
                self.networks_box.add(e)
                entries += 1

            entry = self.networks_box.get_children()[amount]
            entry.set_text(nw.cidr_netaddress())

    def get_addresses(self, event):
        """
        Get hosts for network(s).
        """
        networks = []

        for entry in self.networks_box.get_children()[:-1]:
            text_entry = entry.get_text()
            wrong = alpha.search(text_entry)
            if wrong:
                self._error_invalid_network(text_entry)
                return
            elif text_entry:
                networks.append(text_entry)

        if not networks:
            dlg = HIGAlertDialog(self,
                                 message_format=_("No network."),
                                 secondary_text=_(
                                     "You need to specify at least "
                                     "one network to search for hosts."))
            dlg.run()
            dlg.destroy()
            return

        self.scans = {}
        self.scount = 0

        for n in networks:
            discovery = NmapCommand("%s -sP %s" % ('nmap', n))
            discovery.run_scan()

            self.scans[self.scount] = (discovery, n)
            self.scount += 1

        self.target_model.clear()
        self.hostdetect_btn.set_sensitive(False)
        self._adjust_target_label()
        gobject.timeout_add(500, self._check_scans)

    def _adjust_target_label(self):
        """Update target_lbl according to the current scount (assumes that
        scount > 0)."""
        word = append_s(_("scan"), self.scount)
        self.target_lbl.set_label(
            _("Target list") + (" (%d) " % self.scount) + word + _(" running"))

    def _check_scans(self):
        """
        Check if some scan finished.
        """
        for item in self.scans.items():
            index = item[0]
            scan = item[1][0]
            network = item[1][1]

            if not scan.scan_state():  # scan finished
                np = NmapParser(scan.get_xml_output_file())
                np.parse()
                for host in np.nmap["hosts"]:  # get hosts with 'up' state
                    if host.state == 'up':
                        self.target_model.append((host.ip['addr'], network))

                # remove scan from list
                del self.scans[index]

                self.scount -= 1
                if self.scount:
                    self._adjust_target_label()

                # clean up temp files
                scan.close()

        if self.scount == 0:  # all scans finished
            self.hostdetect_btn.set_sensitive(True)
            self.target_lbl.set_label(_("Target list"))
            return False

        return True

    def _error_invalid_network(self, network):
        """
        Show error dialog for invalid network(s).
        """
        dlg = HIGAlertDialog(
            self,
            message_format=_('Invalid network(s).'),
            secondary_text=(_("There is some invalid character in network") +
                            (" %r" % network) + _("please verify.")))
        dlg.run()
        dlg.destroy()

    def __layout(self):
        """
        Layout widgets
        """
        main_vbox = HIGVBox()
        main_vbox.set_border_width(5)
        main_vbox.set_spacing(12)
        main_hpaned = gtk.HPaned()
        btns_hbox = HIGHBox()
        left_box = HIGVBox()
        right_box = gtk.VBox()

        header_hbox = HIGHBox()
        hostdetect_hbox = HIGHBox()
        targetl_hbox = HIGHBox()
        targetv_hbox = HIGHBox()
        targetr_hbox = HIGHBox()

        # header
        header_hbox._pack_expand_fill(self.ttitle)
        header_hbox._pack_noexpand_nofill(self.umit_logo)
        # network list
        netframe = HIGFrame(_("Network list"))
        settings_align = gtk.Alignment(0.5, 0.5, 1, 1)
        settings_align.set_padding(6, 0, 12, 0)
        nbox = HIGVBox()
        entry = gtk.Entry()
        entry.set_text(_("Sample 192.168.254.0/24"))
        nbox._pack_noexpand_nofill(entry)
        addnw_hbox = HIGHBox()
        addnw_hbox._pack_noexpand_nofill(self.addnetworks)
        nbox.pack_end(addnw_hbox, False, False, 0)
        self.networks_box = nbox
        settings_align.add(nbox)
        netframe.add(settings_align)
        # detection
        hostdetect_hbox._pack_noexpand_nofill(self.netdetect_btn)
        hostdetect_hbox._pack_noexpand_nofill(self.hostdetect_btn)

        # target list
        targetl_hbox._pack_noexpand_nofill(self.target_lbl)
        targetv_hbox._pack_expand_fill(self.tview)
        targetr_hbox.pack_end(self.target_remove, False, False, 0)

        # bottom buttons
        btns_hbox.set_homogeneous(True)
        btns_hbox._pack_expand_fill(self.help)
        btns_hbox._pack_expand_fill(hig_box_space_holder())
        btns_hbox._pack_expand_fill(self.cancel)
        btns_hbox._pack_expand_fill(self.apply)
        # change apply button stock text
        lbl = self.apply.get_children()[0].get_children()[0].get_children()[1]
        lbl.set_text(_("Use target list"))

        left_box._pack_noexpand_nofill(netframe)
        left_box.pack_end(hostdetect_hbox, False, False, 0)
        right_box.pack_start(targetl_hbox, False, False, 0)
        right_box.pack_start(targetv_hbox, True, True, 6)
        right_box.pack_start(targetr_hbox, False, False, 0)

        left_align = gtk.Alignment(0.5, 0.5, 1, 1)
        left_align.set_padding(0, 0, 0, 6)
        left_align.add(left_box)
        right_align = gtk.Alignment(0.5, 0.5, 1, 1)
        right_align.set_padding(0, 0, 6, 0)
        right_align.add(right_box)

        main_hpaned.add1(left_align)
        main_hpaned.add2(right_align)

        main_vbox._pack_noexpand_nofill(header_hbox)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_expand_fill(main_hpaned)
        main_vbox.pack_end(btns_hbox, False, False, 0)

        self.add(main_vbox)
Exemplo n.º 12
0
class HostDiscovery(gtk.Window):
    """
    GUI for network/host discovery.
    """

    def __init__(self, daddy):
        gtk.Window.__init__(self)

        self.daddy = daddy
        self.rowsel = None
        self.tooltips = gtk.Tooltips()
        self.wtitle = _("Host Discovery")

        # header
        self.title_markup = "<span size='16500' weight='heavy'>%s</span>"
        self.ttitle = HIGEntryLabel("")
        self.ttitle.set_line_wrap(False)
        self.ttitle.set_markup(self.title_markup % self.wtitle)
        self.umit_logo = gtk.Image()
        self.umit_logo.set_from_file(logo)
        # discovery options
        self.netdetect_btn = gtk.Button(_("Detect network(s)"))
        self.netdetect_btn.connect('clicked', self.get_networks)
        self.networks_box = None
        self.addnetworks = gtk.Button(_("Add new entry"))
        self.addnetworks.connect('clicked', self._create_network_entry)
        self.hostdetect_btn = gtk.Button(_("Find hosts"))
        self.hostdetect_btn.connect('clicked', self.get_addresses)
        # target list
        self.target_lbl = HIGEntryLabel(_("Target list"))
        self.target_model = gtk.ListStore(gobject.TYPE_STRING,
            gobject.TYPE_STRING)
        self.tview = gtk.TreeView(self.target_model)
        self.tview.set_size_request(300, int(300/1.6))
        self.tview.columns = [None]*2
        self.tview.columns[0] = gtk.TreeViewColumn(_("Host"))
        self.tview.columns[1] = gtk.TreeViewColumn(_("Network"))
        for n in range(2):
            self.tview.append_column(self.tview.columns[n])
            self.tview.columns[n].cell = gtk.CellRendererText()
            self.tview.columns[n].pack_start(self.tview.columns[n].cell, True)
            self.tview.columns[n].set_attributes(self.tview.columns[n].cell,
                                                 text=n)
        self.tview.get_selection().connect('changed', self._tview_sel_change)
        self.target_remove = gtk.Button(_("Remove from list"))
        self.target_remove.set_sensitive(False)
        self.target_remove.connect('clicked', self._remove_target)
        # bottom buttons
        self.help = HIGButton(stock=gtk.STOCK_HELP)
        self.help.connect('clicked', self._show_help)
        self.cancel = HIGButton(stock=gtk.STOCK_CANCEL)
        self.cancel.connect('clicked', self._exit)
        self.apply = HIGButton(stock=gtk.STOCK_APPLY)
        self.apply.connect('clicked', self._return_list)

        # tooltips
        self.tooltips.set_tip(self.addnetworks,
            _("Add new entry for a network"))
        self.tooltips.set_tip(self.netdetect_btn,
            _("Try to detect network(s)"))
        self.tooltips.set_tip(self.hostdetect_btn,
            _("Find hosts in entered network(s)"))
        self.tooltips.set_tip(self.target_remove,
            _("Remove selection from target list"))


        self.__layout()


    def _create_network_entry(self, event):
        """
        Create a new network entry.
        """
        entry = gtk.Entry()
        entry.set_text('')
        entry.show()
        self.networks_box.add(entry)


    def _tview_sel_change(self, event):
        """
        Row selection changed in treeview.
        """
        model, tv_iter = event.get_selected()
        self.rowsel = tv_iter
        self.target_remove.set_sensitive(True)


    def _remove_target(self, event):
        """
        Remove a host from target list.
        """
        if self.rowsel:
            self.target_model.remove(self.rowsel)
            self.target_remove.set_sensitive(False)
            self.rowsel = None


    def _show_help(self, event):
        """
        Show help.
        """
        pass


    def _exit(self, event):
        """
        Close window.
        """
        self.daddy.discoverywin = None # daddy is NewInventory instance
        self.destroy()


    def _return_list(self, event):
        """
        Return target list.
        """
        hosts = [ ]
        for row in self.target_model:
            hosts.append(row[0])

        self.results = ' '.join([str(h) for h in hosts])

        if self.daddy: # NewInventory instance
            self.daddy.scantarget.set_text(self.results)

        self._exit(None)


    def get_networks(self, event):
        """
        Try to detect network(s).
        """
        networks = tryto_detect_networks()

        if not networks:
            dlg = HIGAlertDialog(self,
                message_format=_("No network(s) detected."),
                secondary_text=_("You will need to especify the "
                    "network(s) yourself before detecting hosts."))
            dlg.run()
            dlg.destroy()
            return

        entries = len(self.networks_box.get_children()) - 1

        for amount, nw in enumerate(networks):
            if amount == entries:
                e = gtk.Entry()
                e.set_text('')
                e.show()
                self.networks_box.add(e)
                entries += 1

            entry = self.networks_box.get_children()[amount]
            entry.set_text(nw.cidr_netaddress())


    def get_addresses(self, event):
        """
        Get hosts for network(s).
        """
        networks = []

        for entry in self.networks_box.get_children()[:-1]:
            text_entry = entry.get_text()
            wrong = alpha.search(text_entry)
            if wrong:
                self._error_invalid_network(text_entry)
                return
            elif text_entry:
                networks.append(text_entry)

        if not networks:
            dlg = HIGAlertDialog(self, message_format=_("No network."),
                secondary_text=_("You need to specify at least "
                    "one network to search for hosts."))
            dlg.run()
            dlg.destroy()
            return

        self.scans = { }
        self.scount = 0

        for n in networks:
            discovery = NmapCommand("%s -sP %s" % ('nmap', n))
            discovery.run_scan()

            self.scans[self.scount] = (discovery, n)
            self.scount += 1

        self.target_model.clear()
        self.hostdetect_btn.set_sensitive(False)
        self._adjust_target_label()
        gobject.timeout_add(500, self._check_scans)


    def _adjust_target_label(self):
        """Update target_lbl according to the current scount (assumes that
        scount > 0)."""
        word = append_s(_("scan"), self.scount)
        self.target_lbl.set_label(
                _("Target list") +
                (" (%d) " % self.scount) + word +
                _(" running"))


    def _check_scans(self):
        """
        Check if some scan finished.
        """
        for item in self.scans.items():
            index = item[0]
            scan = item[1][0]
            network = item[1][1]

            if not scan.scan_state(): # scan finished
                np = NmapParser(scan.get_xml_output_file())
                np.parse()
                for host in np.nmap["hosts"]: # get hosts with 'up' state
                    if host.state == 'up':
                        self.target_model.append((host.ip['addr'], network))

                # remove scan from list
                del self.scans[index]

                self.scount -= 1
                if self.scount:
                    self._adjust_target_label()

                # clean up temp files
                scan.close()

        if self.scount == 0: # all scans finished
            self.hostdetect_btn.set_sensitive(True)
            self.target_lbl.set_label(_("Target list"))
            return False

        return True


    def _error_invalid_network(self, network):
        """
        Show error dialog for invalid network(s).
        """
        dlg = HIGAlertDialog(self, message_format=_('Invalid network(s).'),
            secondary_text=(
                _("There is some invalid character in network") +
                    (" %r" % network) + _("please verify.")))
        dlg.run()
        dlg.destroy()


    def __layout(self):
        """
        Layout widgets
        """
        main_vbox = HIGVBox()
        main_vbox.set_border_width(5)
        main_vbox.set_spacing(12)
        main_hpaned = gtk.HPaned()
        btns_hbox = HIGHBox()
        left_box = HIGVBox()
        right_box = gtk.VBox()

        header_hbox = HIGHBox()
        hostdetect_hbox = HIGHBox()
        targetl_hbox = HIGHBox()
        targetv_hbox = HIGHBox()
        targetr_hbox = HIGHBox()

        # header
        header_hbox._pack_expand_fill(self.ttitle)
        header_hbox._pack_noexpand_nofill(self.umit_logo)
        # network list
        netframe = HIGFrame(_("Network list"))
        settings_align = gtk.Alignment(0.5, 0.5, 1, 1)
        settings_align.set_padding(6, 0, 12, 0)
        nbox = HIGVBox()
        entry = gtk.Entry()
        entry.set_text(_("Sample 192.168.254.0/24"))
        nbox._pack_noexpand_nofill(entry)
        addnw_hbox = HIGHBox()
        addnw_hbox._pack_noexpand_nofill(self.addnetworks)
        nbox.pack_end(addnw_hbox, False, False, 0)
        self.networks_box = nbox
        settings_align.add(nbox)
        netframe.add(settings_align)
        # detection
        hostdetect_hbox._pack_noexpand_nofill(self.netdetect_btn)
        hostdetect_hbox._pack_noexpand_nofill(self.hostdetect_btn)

        # target list
        targetl_hbox._pack_noexpand_nofill(self.target_lbl)
        targetv_hbox._pack_expand_fill(self.tview)
        targetr_hbox.pack_end(self.target_remove, False, False, 0)

        # bottom buttons
        btns_hbox.set_homogeneous(True)
        btns_hbox._pack_expand_fill(self.help)
        btns_hbox._pack_expand_fill(hig_box_space_holder())
        btns_hbox._pack_expand_fill(self.cancel)
        btns_hbox._pack_expand_fill(self.apply)
        # change apply button stock text
        lbl = self.apply.get_children()[0].get_children()[0].get_children()[1]
        lbl.set_text(_("Use target list"))


        left_box._pack_noexpand_nofill(netframe)
        left_box.pack_end(hostdetect_hbox, False, False, 0)
        right_box.pack_start(targetl_hbox, False, False, 0)
        right_box.pack_start(targetv_hbox, True, True, 6)
        right_box.pack_start(targetr_hbox, False, False, 0)

        left_align = gtk.Alignment(0.5, 0.5, 1, 1)
        left_align.set_padding(0, 0, 0, 6)
        left_align.add(left_box)
        right_align = gtk.Alignment(0.5, 0.5, 1, 1)
        right_align.set_padding(0, 0, 6, 0)
        right_align.add(right_box)

        main_hpaned.add1(left_align)
        main_hpaned.add2(right_align)

        main_vbox._pack_noexpand_nofill(header_hbox)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_expand_fill(main_hpaned)
        main_vbox.pack_end(btns_hbox, False, False, 0)

        self.add(main_vbox)