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

Revision 1426, 17.6 kB (checked in by kop-labs, 6 years ago)

Delete Dependences

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, CommandContainer, command_manager
49from umitInterfaceEditor.RestructFiles import RestructFiles
50from umitInterfaceEditor.DependencesOption import DependenceOption
51
52from umitInterfaceEditor.PageNotebook import CommandAddRemoveOption, CommandAddRemoveVoidplace
53
54'''
55Contains a Display, and the List of Options
56to use in the GUI UIE
57It's a sub-file of UIE
58'''
59
60class CommandAddRemoveOptionMode(TwiceCommand, Command):
61    def __init__(self, option, optioncore,modeltreeview,optiondisplay, state):
62        TwiceCommand.__init__(self, state)
63        Command.__init__(self, 'Add / Remove a Option')
64        self._option = option
65        self.options = optioncore
66        self.__model = modeltreeview
67        self.optionlist = optiondisplay.optionlist
68        self.optiondisplay = optiondisplay
69       
70   
71    def _add_option(self):
72        option = self._option
73        opt = option.get_option_dic()
74        self.options.add_option_from_dic(opt)
75       
76        myiter = self.__model.insert_before(None, None)
77        arg = option.get_arg_type()
78        icon = gtk.Image()
79        s = self.optionlist._arg_img(arg)
80        img_dir =  os.path.join(pixmaps_dir, '%s.png' % s)
81        icon.set_from_file(img_dir)
82        icon = icon.get_pixbuf()
83        self.__model.set_value(myiter, 0, icon)
84        self.__model.set_value(myiter, 1, option.get_name())
85        self.options.reload_opt()
86
87    _execute_1 = _add_option
88    def _remove_option(self):
89        name = self._option.get_name()
90       
91        self.options.remove_option(name)
92
93        #Update treeview
94        (model,iter) = self.optionlist.get_selected_option()
95        model.remove(iter)     
96        self.optiondisplay.clear()
97       
98    _execute_2 = _remove_option
99   
100
101
102class OptionDisplay(HIGTable):
103    def __init__(self, option=None):
104        HIGTable.__init__(self)
105        self.create_and_attach_widgets()
106        self.set_border_width(5)
107        self.arg_type=None
108   
109    def create_and_attach_widgets(self):
110        self.option_label = HIGSectionLabel('New Option')
111        self.option_label.set_width_chars(10)
112        self.attach(self.option_label, 0, 1, 0, 1)
113
114        self.name_label = HIGEntryLabel(_('Name:'))
115        self.name_entry = HIGTextEntry()
116        self.attach(self.name_label, 0,1,1,2)
117        self.attach(self.name_entry, 1,3,1,2)
118       
119        self.hint_label = HIGEntryLabel(_('Hint:'))
120        self.hint_entry = HIGTextEntry()
121        self.attach(self.hint_label, 0,1,2,3)
122        self.attach(self.hint_entry,1,3,2,3)
123
124        self.need_root = gtk.CheckButton(_('Need root'))
125        self.attach(self.need_root, 0,1,3,4)   
126       
127     
128       
129        self.options_label = HIGEntryLabel(_('Options:'))
130        hbox = HIGHBox()
131        self.options_entry = HIGTextEntry()
132        self.insert_arg_button = HIGButton(title='Args', stock='gtk-add')
133        self.insert_arg_button.connect('clicked', self.update_args)
134        self.attach(self.options_label,0,1,4,5)
135        self.attach(self.options_entry, 1,2,4,5)
136        self.attach(self.insert_arg_button, 2,3, 4, 5)
137       
138        self.aguments_label = HIGEntryLabel(_('Arguments:'))
139        self.arguments_entry = HIGTextEntry()
140        self.arguments_entry.set_editable(False)
141        self.attach(self.aguments_label, 0,1, 5,6)
142        self.attach(self.arguments_entry, 1,3,5,6)     
143       
144   
145    def update_args(self, widget):
146        '''
147        Update aguments entry and option entry
148        '''     
149       
150        cursor_index = self.options_entry.get_position()
151        text_entry = self.options_entry.get_text()
152        arg_description, arg_key = self.dialog_args()
153        if arg_key != None :
154            #Update arguments
155           
156            self.arg_type = arg_key
157            if text_entry.find('%s') == -1: 
158                left = text_entry[0:cursor_index]
159                right = text_entry[cursor_index:len(text_entry)]
160                final = left + "%s" + right
161                self.options_entry.set_text(final)
162            self.arguments_entry.set_text(arg_description)     
163           
164       
165    def dialog_args(self):
166        '''
167        Create a dialog
168        '''
169       
170        d = HIGDialog(_('Arguments'))
171        description_label = HIGEntryLabel(
172            _('Insert the description to argument:'))
173        description_label.show()
174        description_entry = HIGTextEntry()
175        text = self.arguments_entry.get_text()
176        description_entry.set_text(text)
177        description_entry.show()
178       
179        combo_box = gtk.combo_box_new_text()
180        combo_box.set_wrap_width(1)
181        index = -1 
182        j = 0 
183        for i in ARG_TYPES:
184            combo_box.append_text(ARG_TYPES[i])
185            if i == self.arg_type:
186                index = j
187            j = j + 1
188        if index > -1 : 
189            combo_box.set_active(index)
190        combo_box.show()
191        d.vbox.pack_start(description_label, False, False)
192        d.vbox.pack_start(description_entry, False, False)
193        d.vbox.pack_start(combo_box, False, False)
194        d.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
195        d.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)
196        resp = d.run()
197        result  = None, None 
198        if resp == gtk.RESPONSE_OK:
199            model = combo_box.get_model()
200            active = combo_box.get_active()
201            if active < 0:
202                return None, None 
203            combo_selected =  model[active][0]
204           
205            for i in ARG_TYPES:
206                if combo_selected == ARG_TYPES[i]:
207                    combo_selected = i
208               
209            result = description_entry.get_text(), combo_selected
210            #self.insert_arg_button.set_label('Edit args')
211            #self.insert_arg_button.
212        d.destroy()
213        return result
214   
215    def clear(self):
216        """
217        Clear Option Display
218        """
219        self.option_label.set_new_text('New Option')
220        self.name_entry.set_text('')
221        self.hint_entry.set_text('')
222        self.arguments_entry.set_text('')
223        self.need_root.set_active(False)
224        self.options_entry.set_text('')
225       
226       
227    def set_option_list(self, list):
228        """
229        set option list from a dictionarie
230       
231        @param list: Elements of a option
232        @type list: Dictionarie with elements
233        """
234        self.clear()
235        self.option_label.set_new_text(list['name'])
236        self.name_entry.set_text(list['name'])
237        self.hint_entry.set_text(list['hint'])
238   
239        for i in list['arguments']:
240            i = self.arguments_entry.get_text() + i
241            self.arguments_entry.set_text(i)
242       
243        self.options_entry.set_text(list['option'])
244        self.need_root.set_active(list['need_root'])
245        self.arg_type = list['arg_type']
246       
247       
248    def set_option(self,name, hint,
249                   arguments, need_root, 
250                   options, arg_type):       
251        """
252        fill fields
253        buggy arguments.
254        """
255        self.clear()
256        self.options_entry.set_label(name)
257        self.name_entry.set_text(name)
258        self.hint_entry.set_text(hint)
259        self.arguments_entry.set_text(arguments)
260        self.need_root.set_active(need_root)
261        self.arg_type = arg_type
262
263class OptionDisplayMainFrame(OptionDisplay):
264    def __init__(self, option=None):
265        OptionDisplay.__init__(self)
266        #Profile and Wizard core
267        self._profilecore = None 
268        self._wizardcore = None 
269        self._notebook= None
270        self._profile = None 
271        self._wizard = None 
272       
273        hbox = HIGHBox()
274        hbox.set_border_width(12)
275        self.delete_button = HIGButton(stock='gtk-delete')
276        self.delete_button.connect('clicked', self.delete_option)
277        self.new_button = HIGButton(stock='gtk-new')
278        self.new_button.connect('clicked', self.new_option)
279        self.update_button = HIGButton(stock='gtk-refresh')
280        self.update_button.connect('clicked', self.update_option)
281        self.add_button = HIGButton(stock='gtk-add')
282        self.add_button.connect('clicked', self.add_option)
283        hbox.pack_end(self.delete_button,False,False)
284        hbox.pack_end(self.update_button, False, False)
285        hbox.pack_end(self.add_button, False, False)
286        hbox.pack_end(self.new_button, False,False)
287        self.attach(hbox, 1,2,6,7)
288
289        self.optionlist = option
290    def set_wizard(self, wizard):
291        self._wizard = wizard
292        self._wizardcore = wizard.get_profilecore()
293    def set_profile(self, profile):
294        self._profile = profile
295        self._profilecore = profile.get_profilecore()
296    def set_options_list(self, options):
297        '''
298        set a OptionList to manipulate when add remove and edit
299        @param options: Options List
300        @type options: class OptionList
301        '''
302       
303        self.optionlist = options
304
305
306    def get_option(self):
307        '''
308        Get a option filled
309        @return: a option
310        @rtype: class Option
311        '''
312
313        name = self.name_entry.get_text()
314        hint = self.hint_entry.get_text()
315        #Args is only to one yet
316        arguments = [self.arguments_entry.get_text()]
317        need_root = self.need_root.get_active()
318        arg_type = self.arg_type
319        options = self.options_entry.get_text()
320        opt = Option(name, options, hint, arguments, need_root, arg_type)
321        return opt
322   
323
324    def delete_option(self, widget):
325        """
326        Delete option
327        @param widget: widget from connect
328        @type widget: HIGButton
329        """
330        name = self.name_entry.get_text()
331        if name == '':
332            d = HIGAlertDialog(type=gtk.MESSAGE_ERROR, 
333                               message_format=_('Invalid option '), 
334                           secondary_text='Fill fields of option')
335            d.run()
336            d.destroy()
337        else:       
338            if self.optionlist.options.exists(name): 
339                #Verify if exists
340                self.rf = RestructFiles(self.optionlist.options, 
341                                        self._wizardcore,
342                                        self._profilecore)
343                profile, wizard =  self.rf.get_places(name)
344                used = []
345                for i in profile:
346                    used.append(i)
347                for i in wizard:
348                    used.append(i)
349                if used == []:
350                    cmd = CommandAddRemoveOptionMode(self.get_option(),
351                                                 self.optionlist.options,
352                                                 self.optionlist.get_model(),
353                                                 self,
354                                                 False)
355                    command_manager.add_command(cmd)
356                else:
357                    #Show Dialog Dependences etc!!!
358                    print used
359                    dep = DependenceOption(name, self.rf, profile, wizard)
360                    resp = dep.run()
361                    dep.destroy()
362                   
363                    if resp == gtk.RESPONSE_YES:
364                        commands = []
365                        for i in profile:
366                            boxedit = self._profile.notebook.get_page_name(i[0])
367                            widget = boxedit.search_option(i[1])
368                            cmd = CommandAddRemoveOption(widget,
369                                                         boxedit,
370                                                         self._profilecore,
371                                                         False)
372                           
373                            cmd2 = CommandAddRemoveVoidplace(boxedit,
374                                                             widget,
375                                                             boxedit._coords,
376                                                             False)
377                            commands.append(cmd)
378                            commands.append(cmd2)
379                        #for i in wizard:
380                        #    print i
381                        cmd = CommandContainer('Remove option and deps',
382                                               True,
383                                               commands)
384                        command_manager.add_command(cmd)
385                   
386                    else: 
387                        return
388                   
389                   
390               
391                #self.optionlist.options.remove_option(name)
392
393                ##Update treeview
394                #(model,iter) = self.optionlist.get_selected_option()
395                #model.remove(iter)     
396                #self.clear()
397               
398            else: 
399                d = HIGAlertDialog(type= gtk.MESSAGE_ERROR, 
400                                   message_format=_('ERROR'),
401                                   secondary_text=_('Option do not exists')
402                               )
403                d.run()
404                d.destroy()
405   
406   
407    def set_notebook(self, notebook):
408        self._notebook = notebook
409   
410    def update_option(self, widget):
411        """
412        Update option
413        @param widget: widget from connect
414        @type widget: HIGButton
415        """
416        name = self.name_entry.get_text()
417        if name == '':
418            d = HIGAlertDialog(type=gtk.MESSAGE_ERROR, 
419                               message_format=_('Invalid name option '), 
420                           secondary_text='Fill fields of option')
421            d.run()
422            d.destroy()
423        else:   
424            if self.optionlist.options.exists(name): 
425                opt = self.get_option()
426                self.optionlist.options.remove_option(name)
427                self.optionlist.add(opt)
428           
429       
430       
431    def new_option(self, widget):
432        """
433        Clean Option Display
434        @param widget: widget from connect
435        @type widget: HIGButton
436        """   
437        self.clear()
438        self.add_button.set_sensitive(True)
439        self.update_button.set_sensitive(False)
440        self.delete_button.set_sensitive(False)
441       
442    def add_option(self, widget):
443        """
444        Add option
445        @param widget: widget from connect
446        @type widget: HIGButton
447        """
448       
449
450        opt = self.get_option()
451        self.optionlist.add(opt)
452        self.add_button.set_sensitive(False)
453       
454
455TARGET_STRING = 0
456TARGET_ROOTWIN = 1
457
458target = [
459    ('STRING', 0, TARGET_STRING),
460    ('text/plain', 0, TARGET_STRING),
461    ('application/x-rootwin-drop', 0, TARGET_ROOTWIN)
462]
463
464class OptionList(HIGVBox):
465    """
466    A treeview with a list of actual options
467    """
468   
469    def __init__(self, optiondisplay=None):
470        HIGVBox.__init__(self)
471        self.__model =  gtk.TreeStore(gtk.gdk.Pixbuf,gobject.TYPE_STRING)
472        self.__treeview = gtk.TreeView(self.__model)
473        self.__treeview.set_headers_visible(True)
474        self.__treeview.drag_source_set(gtk.gdk.BUTTON1_MASK | 
475                                        gtk.gdk.BUTTON3_MASK,
476                                        target, gtk.gdk.ACTION_COPY | 
477                                        gtk.gdk.ACTION_MOVE)
478        self.__treeview.connect('drag_data_get', self.source_drag_data_get)
479        column = gtk.TreeViewColumn()
480        column.set_title('Name')
481        render_pixbuf = gtk.CellRendererPixbuf()
482        column.pack_start(render_pixbuf, expand=False)
483        column.add_attribute(render_pixbuf, 'pixbuf', 0)
484        render_text = gtk.CellRendererText()
485        column.pack_start(render_text, expand=True)
486        column.add_attribute(render_text, 'text', 1)
487        self.__treeview.append_column(column)
488        self.options = ListOptions(options)
489        self.__scrolledwindow = HIGScrolledWindow()
490        self.__scrolledwindow.set_policy(gtk.POLICY_AUTOMATIC,
491                                         gtk.POLICY_AUTOMATIC)
492        self.pack_start(self.__scrolledwindow, True, True )
493        self.__scrolledwindow.add(self.__treeview)
494        self.optiondisplay = optiondisplay
495       
496        self.exists_display = (self.optiondisplay != None ) #True or False
497        self.set_option_display(optiondisplay)
498    def get_model(self):
499        return self.__model
500    def get_list_option(self):
501        return self.options
502    def source_drag_data_get(self, btn, context, selection_data, info, time):
503
504        param_send = self.get_selected()
505        #param_send = opt
506        selection_data.set(selection_data.target, 8, param_send)
507    def get_selected_option(self):
508        '''
509        @return: iter and model of option treeview selected
510        '''
511        treeselection = self.__treeview.get_selection()
512        (model,iter) = treeselection.get_selected()
513        return model, iter
514
515    def set_option_display(self, optiondisplay):
516        """
517        Set a option display to change fields when cursor change
518       
519        @param optiondisplay: it's a mainframe that contains fields to set
520        @type optiondisplay: OptionDisplay
521        """
522       
523        self.optiondisplay = optiondisplay
524        self.exists_display = (self.optiondisplay != None ) #True or False
525        if self.exists_display:
526            log.debug('<<< Cursor changed')
527            self.__treeview.connect("cursor-changed",self.update_option_display)
528           
529           
530    def get_selected(self):
531        """
532        Returns the string with name of selected option
533        """
534        try:
535            treeselection = self.__treeview.get_selection()
536            (model,iter) = treeselection.get_selected() 
537            return model.get_value(iter,1)
538        except:
539            return None           
540           
541    def update_option_display(self, widget):
542        """
543        Update option display contents
544        """
545        if self.get_selected()==None :
546            return
547        option = self.options.get_option(self.get_selected())
548        self.optiondisplay.set_option_list(option)
549        self.optiondisplay.add_button.set_sensitive(False)
550        self.optiondisplay.update_button.set_sensitive(True)   
551        self.optiondisplay.delete_button.set_sensitive(True)
552   
553    def _arg_img(self, arg):
554        if arg == 'str':
555            return 'entry'
556        elif arg == 'int':
557            return 'spinbutton'
558        elif arg == '' :
559            return 'checkbutton'
560        return 'label'
561    def reload(self):
562        """
563        Reload items of treeview
564        """
565       
566        list = self.options.get_options_list()
567        for i in list:
568            arg = self.options.get_arg_type(i)
569            myiter = self.__model.insert_before(None, None)
570            icon = gtk.Image()
571            s = self._arg_img(arg)
572            img_dir =  os.path.join(pixmaps_dir, '%s.png' % s)
573            icon.set_from_file(img_dir)
574            icon = icon.get_pixbuf()
575            self.__model.set_value(myiter, 0, icon)
576            self.__model.set_value(myiter, 1, i)
577
578
579    def add(self, option):
580        """
581        Add a new option
582        """
583        cmd = CommandAddRemoveOptionMode(option, 
584                                         self.options, 
585                                         self.__model,
586                                         self.optiondisplay,
587                                         True)
588        command_manager.add_command(cmd)
589       
590       
591        #opt = option.get_option_dic()
592        #self.options.add_option_from_dic(opt)
593       
594        #myiter = self.__model.insert_before(None, None)
595        #arg = option.get_arg_type()
596        #icon = gtk.Image()
597        #s = self._arg_img(arg)
598        #img_dir =  os.path.join(pixmaps_dir, '%s.png' % s)
599        #icon.set_from_file(img_dir)
600        #icon = icon.get_pixbuf()
601        #self.__model.set_value(myiter, 0, icon)
602        #self.__model.set_value(myiter, 1, option.get_name())
603        #self.options.reload_opt()
604
605
606
607    def save(self):
608        """
609        Save from option treeview to xml file
610        """
611        self.options.write_file(options)
612
613
614if __name__ == "__main__":
615    o = OptionList()
616   
617   
Note: See TracBrowser for help on using the browser.