root/branch/k0p/umitInterfaceEditor/OptionManager.py @ 1424

Revision 1424, 16.4 kB (checked in by kop-labs, 6 years ago)

Dependence Option

Line 
1#!/usr/bin/env python
2# Copyright (C) 2005 Insecure.Com LLC.
3#
4# Author: Luis A. Bastiao Silva <luis.kop@gmail.com>
5#
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19
20import gtk
21import os
22
23from higwidgets.higtables import HIGTable
24from higwidgets.higboxes import HIGVBox, HIGHBox
25from higwidgets.higscrollers import HIGScrolledWindow
26from higwidgets.higlabels import HIGSectionLabel, HIGEntryLabel
27from higwidgets.higentries import HIGTextEntry
28from higwidgets.hignotebooks import HIGNotebook
29from higwidgets.higbuttons import HIGButton
30from higwidgets.higdialogs import HIGDialog, HIGAlertDialog
31from umitCore.Logging import log
32from umitCore.I18N import _
33## Testing at devel
34from os.path import split, join
35
36from umitCore.Paths import Path
37#Path.set_umit_conf(join(split(__file__)[0], 'config', 'umit.conf'))
38##END DEV TEST
39options = Path.options
40pixmaps_dir = Path.pixmaps_dir
41
42import gobject
43from umitInterfaceEditor.ProfileCore import ProfileOption
44from umitGUI.OptionBuilder import OptionBuilder
45from umitCore.NmapOptions import  NmapOptions
46from umitInterfaceEditor.OptionsCore import ListOptions, Option, ARG_TYPES
47
48from umitInterfaceEditor.Command import Command, TwiceCommand, command_manager
49from umitInterfaceEditor.RestructFiles import RestructFiles
50from umitInterfaceEditor.DependencesOption import DependenceOption
51
52'''
53Contains a Display, and the List of Options
54to use in the GUI UIE
55It's a sub-file of UIE
56'''
57
58class CommandAddRemoveOptionMode(TwiceCommand, Command):
59    def __init__(self, option, optioncore,modeltreeview,optiondisplay, state):
60        TwiceCommand.__init__(self, state)
61        Command.__init__(self, 'Add / Remove a Option')
62        self._option = option
63        self.options = optioncore
64        self.__model = modeltreeview
65        self.optionlist = optiondisplay.optionlist
66        self.optiondisplay = optiondisplay
67       
68   
69    def _add_option(self):
70        option = self._option
71        opt = option.get_option_dic()
72        self.options.add_option_from_dic(opt)
73       
74        myiter = self.__model.insert_before(None, None)
75        arg = option.get_arg_type()
76        icon = gtk.Image()
77        s = self.optionlist._arg_img(arg)
78        img_dir =  os.path.join(pixmaps_dir, '%s.png' % s)
79        icon.set_from_file(img_dir)
80        icon = icon.get_pixbuf()
81        self.__model.set_value(myiter, 0, icon)
82        self.__model.set_value(myiter, 1, option.get_name())
83        self.options.reload_opt()
84
85    _execute_1 = _add_option
86    def _remove_option(self):
87        name = self._option.get_name()
88       
89        self.options.remove_option(name)
90
91        #Update treeview
92        (model,iter) = self.optionlist.get_selected_option()
93        model.remove(iter)     
94        self.optiondisplay.clear()
95       
96    _execute_2 = _remove_option
97   
98
99
100class OptionDisplay(HIGTable):
101    def __init__(self, option=None):
102        HIGTable.__init__(self)
103        self.create_and_attach_widgets()
104        self.set_border_width(5)
105        self.arg_type=None
106   
107    def create_and_attach_widgets(self):
108        self.option_label = HIGSectionLabel('New Option')
109        self.option_label.set_width_chars(10)
110        self.attach(self.option_label, 0, 1, 0, 1)
111
112        self.name_label = HIGEntryLabel(_('Name:'))
113        self.name_entry = HIGTextEntry()
114        self.attach(self.name_label, 0,1,1,2)
115        self.attach(self.name_entry, 1,3,1,2)
116       
117        self.hint_label = HIGEntryLabel(_('Hint:'))
118        self.hint_entry = HIGTextEntry()
119        self.attach(self.hint_label, 0,1,2,3)
120        self.attach(self.hint_entry,1,3,2,3)
121
122        self.need_root = gtk.CheckButton(_('Need root'))
123        self.attach(self.need_root, 0,1,3,4)   
124       
125     
126       
127        self.options_label = HIGEntryLabel(_('Options:'))
128        hbox = HIGHBox()
129        self.options_entry = HIGTextEntry()
130        self.insert_arg_button = HIGButton(title='Args', stock='gtk-add')
131        self.insert_arg_button.connect('clicked', self.update_args)
132        self.attach(self.options_label,0,1,4,5)
133        self.attach(self.options_entry, 1,2,4,5)
134        self.attach(self.insert_arg_button, 2,3, 4, 5)
135       
136        self.aguments_label = HIGEntryLabel(_('Arguments:'))
137        self.arguments_entry = HIGTextEntry()
138        self.arguments_entry.set_editable(False)
139        self.attach(self.aguments_label, 0,1, 5,6)
140        self.attach(self.arguments_entry, 1,3,5,6)     
141       
142   
143    def update_args(self, widget):
144        '''
145        Update aguments entry and option entry
146        '''     
147       
148        cursor_index = self.options_entry.get_position()
149        text_entry = self.options_entry.get_text()
150        arg_description, arg_key = self.dialog_args()
151        if arg_key != None :
152            #Update arguments
153           
154            self.arg_type = arg_key
155            if text_entry.find('%s') == -1: 
156                left = text_entry[0:cursor_index]
157                right = text_entry[cursor_index:len(text_entry)]
158                final = left + "%s" + right
159                self.options_entry.set_text(final)
160            self.arguments_entry.set_text(arg_description)     
161           
162       
163    def dialog_args(self):
164        '''
165        Create a dialog
166        '''
167       
168        d = HIGDialog(_('Arguments'))
169        description_label = HIGEntryLabel(
170            _('Insert the description to argument:'))
171        description_label.show()
172        description_entry = HIGTextEntry()
173        text = self.arguments_entry.get_text()
174        description_entry.set_text(text)
175        description_entry.show()
176       
177        combo_box = gtk.combo_box_new_text()
178        combo_box.set_wrap_width(1)
179        index = -1 
180        j = 0 
181        for i in ARG_TYPES:
182            combo_box.append_text(ARG_TYPES[i])
183            if i == self.arg_type:
184                index = j
185            j = j + 1
186        if index > -1 : 
187            combo_box.set_active(index)
188        combo_box.show()
189        d.vbox.pack_start(description_label, False, False)
190        d.vbox.pack_start(description_entry, False, False)
191        d.vbox.pack_start(combo_box, False, False)
192        d.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
193        d.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)
194        resp = d.run()
195        result  = None, None 
196        if resp == gtk.RESPONSE_OK:
197            model = combo_box.get_model()
198            active = combo_box.get_active()
199            if active < 0:
200                return None, None 
201            combo_selected =  model[active][0]
202           
203            for i in ARG_TYPES:
204                if combo_selected == ARG_TYPES[i]:
205                    combo_selected = i
206               
207            result = description_entry.get_text(), combo_selected
208            #self.insert_arg_button.set_label('Edit args')
209            #self.insert_arg_button.
210        d.destroy()
211        return result
212   
213    def clear(self):
214        """
215        Clear Option Display
216        """
217        self.option_label.set_new_text('New Option')
218        self.name_entry.set_text('')
219        self.hint_entry.set_text('')
220        self.arguments_entry.set_text('')
221        self.need_root.set_active(False)
222        self.options_entry.set_text('')
223       
224       
225    def set_option_list(self, list):
226        """
227        set option list from a dictionarie
228       
229        @param list: Elements of a option
230        @type list: Dictionarie with elements
231        """
232        self.clear()
233        self.option_label.set_new_text(list['name'])
234        self.name_entry.set_text(list['name'])
235        self.hint_entry.set_text(list['hint'])
236   
237        for i in list['arguments']:
238            i = self.arguments_entry.get_text() + i
239            self.arguments_entry.set_text(i)
240       
241        self.options_entry.set_text(list['option'])
242        self.need_root.set_active(list['need_root'])
243        self.arg_type = list['arg_type']
244       
245       
246    def set_option(self,name, hint,
247                   arguments, need_root, 
248                   options, arg_type):       
249        """
250        fill fields
251        buggy arguments.
252        """
253        self.clear()
254        self.options_entry.set_label(name)
255        self.name_entry.set_text(name)
256        self.hint_entry.set_text(hint)
257        self.arguments_entry.set_text(arguments)
258        self.need_root.set_active(need_root)
259        self.arg_type = arg_type
260
261class OptionDisplayMainFrame(OptionDisplay):
262    def __init__(self, option=None):
263        OptionDisplay.__init__(self)
264        #Profile and Wizard core
265        self._profilecore = None 
266        self._wizardcore = None 
267       
268        hbox = HIGHBox()
269        hbox.set_border_width(12)
270        self.delete_button = HIGButton(stock='gtk-delete')
271        self.delete_button.connect('clicked', self.delete_option)
272        self.new_button = HIGButton(stock='gtk-new')
273        self.new_button.connect('clicked', self.new_option)
274        self.update_button = HIGButton(stock='gtk-refresh')
275        self.update_button.connect('clicked', self.update_option)
276        self.add_button = HIGButton(stock='gtk-add')
277        self.add_button.connect('clicked', self.add_option)
278        hbox.pack_end(self.delete_button,False,False)
279        hbox.pack_end(self.update_button, False, False)
280        hbox.pack_end(self.add_button, False, False)
281        hbox.pack_end(self.new_button, False,False)
282        self.attach(hbox, 1,2,6,7)
283
284        self.optionlist = option
285    def set_wizardcore(self, wizardcore):
286        self._wizardcore = wizardcore
287    def set_profilecore(self, profilecore):
288        self._profilecore = profilecore
289    def set_options_list(self, options):
290        '''
291        set a OptionList to manipulate when add remove and edit
292        @param options: Options List
293        @type options: class OptionList
294        '''
295       
296        self.optionlist = options
297
298
299    def get_option(self):
300        '''
301        Get a option filled
302        @return: a option
303        @rtype: class Option
304        '''
305
306        name = self.name_entry.get_text()
307        hint = self.hint_entry.get_text()
308        #Args is only to one yet
309        arguments = [self.arguments_entry.get_text()]
310        need_root = self.need_root.get_active()
311        arg_type = self.arg_type
312        options = self.options_entry.get_text()
313        opt = Option(name, options, hint, arguments, need_root, arg_type)
314        return opt
315
316    def delete_option(self, widget):
317        """
318        Delete option
319        @param widget: widget from connect
320        @type widget: HIGButton
321        """
322        name = self.name_entry.get_text()
323        if name == '':
324            d = HIGAlertDialog(type=gtk.MESSAGE_ERROR, 
325                               message_format=_('Invalid option '), 
326                           secondary_text='Fill fields of option')
327            d.run()
328            d.destroy()
329        else:       
330            if self.optionlist.options.exists(name): 
331                #Verify if exists
332                self.rf = RestructFiles(self.optionlist.options, 
333                                        self._wizardcore,
334                                        self._profilecore)
335                used = self.rf.get_places(name)
336                if used == []:
337                    cmd = CommandAddRemoveOptionMode(self.get_option(),
338                                                 self.optionlist.options,
339                                                 self.optionlist.get_model(),
340                                                 self,
341                                                 False)
342                    command_manager.add_command(cmd)
343                else:
344                    #Show Dialog Dependences etc!!!
345                    dep = DependenceOption(name, self.rf, used)
346                    dep.run()
347                    pass
348               
349                #self.optionlist.options.remove_option(name)
350
351                ##Update treeview
352                #(model,iter) = self.optionlist.get_selected_option()
353                #model.remove(iter)     
354                #self.clear()
355               
356            else: 
357                d = HIGAlertDialog(type= gtk.MESSAGE_ERROR, 
358                                   message_format=_('ERROR'),
359                                   secondary_text=_('Option do not exists')
360                               )
361                d.run()
362                d.destroy()
363       
364    def update_option(self, widget):
365        """
366        Update option
367        @param widget: widget from connect
368        @type widget: HIGButton
369        """
370        name = self.name_entry.get_text()
371        if name == '':
372            d = HIGAlertDialog(type=gtk.MESSAGE_ERROR, 
373                               message_format=_('Invalid name option '), 
374                           secondary_text='Fill fields of option')
375            d.run()
376            d.destroy()
377        else:   
378            if self.optionlist.options.exists(name): 
379                opt = self.get_option()
380                self.optionlist.options.remove_option(name)
381                self.optionlist.add(opt)
382           
383       
384       
385    def new_option(self, widget):
386        """
387        Clean Option Display
388        @param widget: widget from connect
389        @type widget: HIGButton
390        """   
391        self.clear()
392        self.add_button.set_sensitive(True)
393        self.update_button.set_sensitive(False)
394        self.delete_button.set_sensitive(False)
395       
396    def add_option(self, widget):
397        """
398        Add option
399        @param widget: widget from connect
400        @type widget: HIGButton
401        """
402       
403
404        opt = self.get_option()
405        self.optionlist.add(opt)
406        self.add_button.set_sensitive(False)
407       
408
409TARGET_STRING = 0
410TARGET_ROOTWIN = 1
411
412target = [
413    ('STRING', 0, TARGET_STRING),
414    ('text/plain', 0, TARGET_STRING),
415    ('application/x-rootwin-drop', 0, TARGET_ROOTWIN)
416]
417
418class OptionList(HIGVBox):
419    """
420    A treeview with a list of actual options
421    """
422   
423    def __init__(self, optiondisplay=None):
424        HIGVBox.__init__(self)
425        self.__model =  gtk.TreeStore(gtk.gdk.Pixbuf,gobject.TYPE_STRING)
426        self.__treeview = gtk.TreeView(self.__model)
427        self.__treeview.set_headers_visible(True)
428        self.__treeview.drag_source_set(gtk.gdk.BUTTON1_MASK | 
429                                        gtk.gdk.BUTTON3_MASK,
430                                        target, gtk.gdk.ACTION_COPY | 
431                                        gtk.gdk.ACTION_MOVE)
432        self.__treeview.connect('drag_data_get', self.source_drag_data_get)
433        column = gtk.TreeViewColumn()
434        column.set_title('Name')
435        render_pixbuf = gtk.CellRendererPixbuf()
436        column.pack_start(render_pixbuf, expand=False)
437        column.add_attribute(render_pixbuf, 'pixbuf', 0)
438        render_text = gtk.CellRendererText()
439        column.pack_start(render_text, expand=True)
440        column.add_attribute(render_text, 'text', 1)
441        self.__treeview.append_column(column)
442        self.options = ListOptions(options)
443        self.__scrolledwindow = HIGScrolledWindow()
444        self.__scrolledwindow.set_policy(gtk.POLICY_AUTOMATIC,
445                                         gtk.POLICY_AUTOMATIC)
446        self.pack_start(self.__scrolledwindow, True, True )
447        self.__scrolledwindow.add(self.__treeview)
448        self.optiondisplay = optiondisplay
449       
450        self.exists_display = (self.optiondisplay != None ) #True or False
451        self.set_option_display(optiondisplay)
452    def get_model(self):
453        return self.__model
454    def get_list_option(self):
455        return self.options
456    def source_drag_data_get(self, btn, context, selection_data, info, time):
457
458        param_send = self.get_selected()
459        #param_send = opt
460        selection_data.set(selection_data.target, 8, param_send)
461    def get_selected_option(self):
462        '''
463        @return: iter and model of option treeview selected
464        '''
465        treeselection = self.__treeview.get_selection()
466        (model,iter) = treeselection.get_selected()
467        return model, iter
468
469    def set_option_display(self, optiondisplay):
470        """
471        Set a option display to change fields when cursor change
472       
473        @param optiondisplay: it's a mainframe that contains fields to set
474        @type optiondisplay: OptionDisplay
475        """
476       
477        self.optiondisplay = optiondisplay
478        self.exists_display = (self.optiondisplay != None ) #True or False
479        if self.exists_display:
480            log.debug('<<< Cursor changed')
481            self.__treeview.connect("cursor-changed",self.update_option_display)
482           
483           
484    def get_selected(self):
485        """
486        Returns the string with name of selected option
487        """
488        try:
489            treeselection = self.__treeview.get_selection()
490            (model,iter) = treeselection.get_selected() 
491            return model.get_value(iter,1)
492        except:
493            return None           
494           
495    def update_option_display(self, widget):
496        """
497        Update option display contents
498        """
499        if self.get_selected()==None :
500            return
501        option = self.options.get_option(self.get_selected())
502        self.optiondisplay.set_option_list(option)
503        self.optiondisplay.add_button.set_sensitive(False)
504        self.optiondisplay.update_button.set_sensitive(True)   
505        self.optiondisplay.delete_button.set_sensitive(True)
506   
507    def _arg_img(self, arg):
508        if arg == 'str':
509            return 'entry'
510        elif arg == 'int':
511            return 'spinbutton'
512        elif arg == '' :
513            return 'checkbutton'
514        return 'label'
515    def reload(self):
516        """
517        Reload items of treeview
518        """
519       
520        list = self.options.get_options_list()
521        for i in list:
522            arg = self.options.get_arg_type(i)
523            myiter = self.__model.insert_before(None, None)
524            icon = gtk.Image()
525            s = self._arg_img(arg)
526            img_dir =  os.path.join(pixmaps_dir, '%s.png' % s)
527            icon.set_from_file(img_dir)
528            icon = icon.get_pixbuf()
529            self.__model.set_value(myiter, 0, icon)
530            self.__model.set_value(myiter, 1, i)
531
532
533    def add(self, option):
534        """
535        Add a new option
536        """
537        cmd = CommandAddRemoveOptionMode(option, 
538                                         self.options, 
539                                         self.__model,
540                                         self.optiondisplay,
541                                         True)
542        command_manager.add_command(cmd)
543       
544       
545        #opt = option.get_option_dic()
546        #self.options.add_option_from_dic(opt)
547       
548        #myiter = self.__model.insert_before(None, None)
549        #arg = option.get_arg_type()
550        #icon = gtk.Image()
551        #s = self._arg_img(arg)
552        #img_dir =  os.path.join(pixmaps_dir, '%s.png' % s)
553        #icon.set_from_file(img_dir)
554        #icon = icon.get_pixbuf()
555        #self.__model.set_value(myiter, 0, icon)
556        #self.__model.set_value(myiter, 1, option.get_name())
557        #self.options.reload_opt()
558
559
560
561    def save(self):
562        """
563        Save from option treeview to xml file
564        """
565        self.options.write_file(options)
566
567
568if __name__ == "__main__":
569    o = OptionList()
570   
571   
Note: See TracBrowser for help on using the browser.