Ejemplo n.º 1
0
    def update(self):
        """
        add data to Category settings

        retrieves data from database for a particular 'catid'
        """
        #/// add data ///

        self.clear_widgets()

        #define structure of fields (like an INI file)
        config = ConfigParser()
        config.add_section('market')
        config.add_section('location')

        #--- set values (needs to come from database)
        #config.set('category','category_name','TestnameID: ' + str(self.catid))
        if self.data == None:
            config.set('market','day','Enter the market DAY here')
            config.set('location','lon','enter longitude here')
            config.set('location','lat','enter latitude here')
            config.set('location','place_name','enter place name here')
            config.set('location','ranking','Ranking here')
            config.set('location','visited',False)
        else:
            config.set('market','day',self.data['day'])

        return config
Ejemplo n.º 2
0
 class AddCardMenuScreen(Screen):
     question = ""
     answer = ""
     def __init__(self):
         Screen.__init__(self)
         self.name = "add"
         
         self.config = ConfigParser()
         self.config.add_section("add")
         self.config.set("add", "question", "Question")
         self.config.set("add", "answer", "Answer")
         self.config.set("add", "make", "action")
         self.config.add_callback(self.update_qa, section="add", key="question")
         self.config.add_callback(self.update_qa, section="add", key="answer")
         self.menu = SettingsWithNoMenu()
         
         
         self.menu.register_type("action", FlashcardAppManager.SettingDoAction)
         self.menu.add_json_panel("Add a card", self.config, os.path.join(os.path.dirname(__file__), 'add_menu.json'))
         
         self.add_widget(self.menu)
         
         
     def update_qa(self, *args):
         FlashcardAppManager.AddCardMenuScreen.question = self.config.get('add', 'question')
         FlashcardAppManager.AddCardMenuScreen.answer = self.config.get('add', 'answer')
Ejemplo n.º 3
0
def Config_GetDefault_Str(*, oConfig: ConfigParser, uSection: str,
                          uOption: str, vDefaultValue: Union[None, bool,
                                                             str]) -> str:
    """
    Replacement for the kivy function

    :param oConfig: The configparser object
    :param uSection: The name of the section
    :param uOption: The name of the option
    :param vDefaultValue: The default value
    :return: The value of an ini setting or the default value
    """
    uDefaultValue: str = u""

    if not oConfig.has_section(uSection):
        oConfig.add_section(uSection)
    if not oConfig.has_option(uSection, uOption):
        if vDefaultValue is not None:
            if type(vDefaultValue) == bool:
                if vDefaultValue:
                    uDefaultValue: str = u'1'
                else:
                    uDefaultValue: str = u'0'
            else:
                uDefaultValue = vDefaultValue
            oConfig.set(uSection, uOption, uDefaultValue)
        return uDefaultValue
    uRetVal: str = ToUnicode(oConfig.get(uSection, uOption))
    return uRetVal
Ejemplo n.º 4
0
 class EditCardMenuScreen(Screen):
     question = ""
     answer = ""
     nquestion = ""
     nanswer = ""
     EditCardMenuConfig = None
     
     def update_qa(self, *args):
             FlashcardAppManager.EditCardMenuScreen.nquestion = self.config.get('edit', 'nquestion')
             FlashcardAppManager.EditCardMenuScreen.nanswer = self.config.get("edit", "nanswer")
             
     def __init__(self):
         Screen.__init__(self)
         
         self.name = "edit"
         
         self.config = ConfigParser()
         self.config.add_section("edit")
         self.config.set("edit", "question", "Question")
         self.config.set("edit", "answer", "Answer")
         self.config.set("edit", "nquestion", "Question")
         self.config.set("edit", "nanswer", "Answer")
         self.config.set("edit", "edit", "action")
         
         FlashcardAppManager.EditCardMenuScreen.question = self.config.get('edit', 'question')
         FlashcardAppManager.EditCardMenuScreen.answer = self.config.get('edit', 'answer')
         FlashcardAppManager.EditCardMenuScreen.nquestion = self.config.get('edit', 'nquestion')
         FlashcardAppManager.EditCardMenuScreen.nanswer = self.config.get('edit', 'nanswer')
         
         
             
         self.config.add_callback(self.update_qa, section="edit", key="nquestion")
         self.config.add_callback(self.update_qa, section="edit", key="nanswer")
         
         self.menu = SettingsWithNoMenu()
         
         
         self.menu.register_type("action", FlashcardAppManager.SettingDoAction)
         self.menu.add_json_panel("Add a card", self.config, os.path.join(os.path.dirname(__file__), 'edit_menu.json'))
         
         FlashcardAppManager.EditCardMenuScreen.EditCardMenuConfig = self.config
         
         self.add_widget(self.menu)
         
         def on_pre_enter(self, *args):
             FlashcardAppManager.EditCardMenuScreen.question = FlashcardAppManager.deck_widget.deck.get_selected().get_question()
             FlashcardAppManager.EditCardMenuScreen.answer = FlashcardAppManager.deck_widget.deck.get_selected().get_answer()
             self.config.set("edit", "question", FlashcardAppManager.EditCardMenuScreen.question)
             self.config.set("edit", "answer", FlashcardAppManager.EditCardMenuScreen.answer)
Ejemplo n.º 5
0
    def update(self):

        self.clear_widgets()

        #define structure of fields (like an INI file)
        config = ConfigParser()
        config.add_section('general')
        config.add_section('location')
        config.add_section('icon_file')

        #--- set values (needs to come from database) todo
        #config.set('general','place_name','Name of the place: ' + str(self.placeid))
        if self.data == None:
            config.set('location','lat','Enter lat here')
            config.set('location','lon','This is a dummy lon.')

            config.set('general','place_name','This is a dummy which should never be seen')
            config.set('general','category_name','This is a dummy which should never be seen')
            config.set('general','ranking','This is a dummy which should never be seen')
            config.set('general','visited','This is a dummy which should never be seen')
            config.set('icon_file','icon_file','This is a dummy which should never be seen')
        else:
            place = self.data
            config.set('location','lat',place.lat)
            config.set('location','lon',place.lon)

            config.set('general','place_name',place.name)

            config.set('general','category_name',place.cat_name )
            config.set('general','ranking', self._ranking2str(place.stars))
            config.set('general','visited',place.status)
            config.set('icon_file','icon_file','Testpath') #todo:how to deal with image data ???

        return config
Ejemplo n.º 6
0
 class MenuScreen(Screen):
     def __init__(self):
         Screen.__init__(self)
         self.name = 'menu'
         self.config = ConfigParser()
         self.config.add_section("deck")
         self.config.add_section("card")
         self.config.adddefaultsection("menu")
         self.config.set("deck", "start_studying", 1)
         self.config.set("deck", "change_deck_mode", "Normal")
         self.config.set("deck", "show_list", True)
         self.config.set("deck", "undo", True)
         self.config.set("deck", "redo", True)
         self.config.set("card", "add", "")
         self.config.set("card", "edit", True)
         self.config.set("card", "remove", True)
         
         self.config.add_callback(self.check_deck_locks, "deck", "redo")
         self.config.add_callback(self.check_deck_locks, "deck", "undo")
         
         self.config.add_callback(self.check_card_locks, "card", "edit")
         self.config.add_callback(self.check_card_locks, "card", "add")
         
         
         self.menu = SettingsWithNoMenu()
         self.menu.register_type("screen", FlashcardAppManager.SettingNewScreen)
         self.menu.register_type("action", FlashcardAppManager.SettingDoAction)
         self.menu.add_json_panel("Flashcards", self.config, os.path.join(os.path.dirname(__file__), 'menu.json'))
         
         self.add_widget(self.menu)
         
 
     def check_deck_locks(self, section, key, value):
         print(self.config.get(section, key))
     
     def check_card_locks(self, section, key, value):
         print()
Ejemplo n.º 7
0
    def update(self):
        """
        add data to Category settings

        retrieves data from database for a particular 'catid'
        """
        #/// add data ///

        self.clear_widgets()

        #define structure of fields (like an INI file)
        config = ConfigParser()
        config.add_section('category')
        config.add_section('icon_file')

        #--- set values (needs to come from database)
        #config.set('category','category_name','TestnameID: ' + str(self.catid))
        if self.data == None:
            config.set('category','category_name','Enter your category name here')
        else:
            config.set('category','category_name',self.data['name'])
        config.set('icon_file','icon_file','Testpath') #todo:how to deal with image data ???

        return config
Ejemplo n.º 8
0
class Settings(object):
    __slots__ = [
        'cfgfilename', 'background_source', 'max_stacksize', 'color_mode',
        'input_channel', 'video_src', 'video_width', 'video_height',
        'show_inp', 'show_out', 'show_vec', 'show_z', 'show_help',
        'stack_status', 'single_thread', 'show_ihist', 'show_ohist', 'out',
        'loop', 'run', 'x_avg', 'y_avg', 'full_avg', 'indzoom', 'indzoominc',
        'log', 'logfile', 'loghandle', 'vecx', 'vecy', 'vecoldx', 'vecoldy',
        'vecxcenter', 'vecycenter', 'vecxoffset', 'vecyoffset', 'out_xcenter',
        'out_xscale', 'out_ycenter', 'out_yscale', 'actuator', 'actuator_parm',
        'dout_active', 'override_active', 'joyx', 'joyy', 'joyxaxis',
        'joyyaxis', 'joyaaxis', 'joybaxis', 'joyhat', 'joyoldx', 'joyoldy',
        'joymaxx', 'joymaxy', 'proc_thread_run', 'proc_fps', 'output_fps',
        'recordi', 'recordv', 'imgindx', 'video', 'output_dir', 'image_dst',
        'blr_inp', 'blr_out', 'blr_strength', 'equ_inp', 'equ_out', 'dnz_inp',
        'dnz_out', 'dnz_inp_str', 'dnz_out_str', 'flt_inp', 'flt_out',
        'flt_inp_strength', 'flt_out_strength', 'flt_inp_kernel',
        'flt_out_kernel', 'trfilter', 'trslope', 'trtrigger', 'trpre', 'trflt',
        'trpref', 'output_file', 'inp_kernel', 'out_kernel', 'flip_x',
        'flip_y', 'mode_prc', 'pseudoc', 'dyn_dark', 'gain_inp', 'gain_out',
        'offset_inp', 'offset_out', 'stb_inp', 'stb_out', 'vec_zoom', 'green',
        'red', 'blue', 'black', 'Config', 'kernels', 'numkernels',
        'flt_inp_name', 'flt_out_name', 'rootwidget', 'imagestack',
        'disp_image', 'oimage', 'iimage', 'act', 'vecz', 'procthread',
        'numframes', 'raspicam', 'timestring', 'cap_prop_frame_width',
        'cap_prop_frame_height', 'cap_prop_pos_frames', 'prop_fourcc',
        'xorvalue', 'xormask1', 'xormask2', 'mask', 'background',
        'actuator_class', 'vectype'
    ]

    def __init__(self):
        self.Config = ConfigParser()
        self.Config.add_section('Input')
        self.Config.add_section('Processor')
        self.Config.add_section('Output')

        # default values
        self.cfgfilename = 'default.conf'
        self.background_source = 'assets/background.png'
        self.max_stacksize = 255  # Max. No. of frames in stack
        self.numframes = 128
        self.color_mode = -1  # Greyscale output
        self.input_channel = 0  # Greyscale input
        self.video_src = 0  # Default camera
        self.video_width = 1024
        self.video_height = 768
        self.show_inp = True
        self.show_out = True
        self.show_vec = False
        self.show_z = True
        self.show_help = False
        self.stack_status = False
        self.single_thread = False
        self.show_ihist = False
        self.show_ohist = False
        self.out = None
        self.background = None
        self.loop = True
        self.run = True
        self.raspicam = False
        self.xorvalue = False
        self.xormask1 = None
        self.xormask2 = None

        # opencv properties
        self.cap_prop_frame_width = 3
        self.cap_prop_frame_height = 4
        self.cap_prop_pos_frames = 1
        self.prop_fourcc = 'YUYV'

        # variables for vector display and actuators
        self.x_avg = 0
        self.y_avg = 0
        self.full_avg = 0
        self.indzoom = 1
        self.indzoominc = 0
        self.log = False
        self.logfile = 'none'
        self.loghandle = None
        self.vecx = 0
        self.vecy = 0
        self.vecoldx = 0
        self.vecoldy = 0
        self.vecxcenter = 0
        self.vecycenter = 0
        self.vecxoffset = 0
        self.vecyoffset = 0
        self.out_xcenter = 0
        self.out_ycenter = 0
        self.out_xscale = 0
        self.out_yscale = 0
        self.actuator = False
        self.actuator_class = 'Paint'
        self.actuator_parm = '127.0.0.1:9003'
        self.dout_active = False
        self.override_active = True
        self.vectype = 1

        # joystick Configuration
        self.joyx = 0
        self.joyy = 0
        self.joyxaxis = 2
        self.joyyaxis = 3
        self.joyaaxis = 0
        self.joybaxis = 1
        self.joyhat = 0
        self.joyoldx = 0
        self.joyoldy = 0
        self.joymaxx = 32768
        self.joymaxy = 32768

        # timing settings for processing and display threads
        self.proc_thread_run = True
        self.proc_fps = 1.0 / 30.0
        self.output_fps = 1.0 / 25.0

        # settings for transient filter
        self.trfilter = False
        self.trslope = 1
        self.trtrigger = 1
        self.trpre = 0
        self.trflt = 0
        self.trpref = 0

        # settings for video and image sequence recording
        self.recordi = False
        self.recordv = False
        self.imgindx = 0
        self.video = None
        self.output_file = None
        self.output_dir = './output/'
        self.image_dst = self.output_dir

        # switches for image filters and tools
        self.blr_inp = False
        self.blr_out = False
        self.blr_strength = 7
        self.equ_inp = 0
        self.equ_out = 0
        self.dnz_inp = False
        self.dnz_out = False
        self.dnz_inp_str = 33
        self.dnz_out_str = 33
        self.flt_inp = 0
        self.flt_out = 0
        self.flt_inp_strength = 0
        self.flt_out_strength = 0
        self.flt_inp_kernel = None
        self.flt_out_kernel = None
        self.flip_x = False
        self.flip_y = False
        self.inp_kernel = None
        self.out_kernel = None
        self.mode_prc = 0
        self.pseudoc = False
        self.dyn_dark = 4
        self.gain_inp = 1.0
        self.gain_out = 1.0
        self.offset_inp = 0
        self.offset_out = 0
        self.stb_inp = False
        self.stb_out = False
        self.vec_zoom = 0.1
        self.green = (0, 255, 0)
        self.red = (0, 0, 255)
        self.blue = (255, 0, 0)
        self.black = (0, 0, 0)
        self.mask = 0
        # self.set_defaults()

    def gettime(self):
        self.timestring = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
        return self.timestring

    def write_config(self, filename, widget):
        if filename is None:
            filename = self.cfgfilename

        # Section 'Input'
        self.Config.set('Input', 'play_mode', widget.playmode_wid.text)
        self.Config.set('Input', 'video_src', self.video_src)
        self.Config.set('Input', 'video_width', self.video_width)
        self.Config.set('Input', 'video_height', self.video_height)
        self.Config.set('Input', 'video_codec', self.prop_fourcc)
        self.Config.set('Input', 'input', widget.inp_wid.state)
        self.Config.set('Input', 'flip_x', widget.flipx_wid.state)
        self.Config.set('Input', 'flip_y', widget.flipy_wid.state)
        self.Config.set('Input', 'blr_inp', widget.iblur_wid.state)
        self.Config.set('Input', 'equ_inp', widget.iequ_wid.text)
        self.Config.set('Input', 'dnz_inp', widget.idnz_wid.state)
        self.Config.set('Input', 'dnz_inp_str', self.dnz_inp_str)
        self.Config.set('Input', 'flt_inp', widget.iflt_wid.text)
        self.Config.set('Input', 'flt_inp_strength', self.flt_inp_strength)
        self.Config.set('Input', 'stb_inp', widget.istab_wid.state)
        self.Config.set('Input', 'gain_inp', widget.igain_wid.value)
        self.Config.set('Input', 'offset_inp', widget.ioffset_wid.value)
        self.Config.set('Input', 'color_channel', widget.ichan_wid.text)

        # Section 'Processor'
        self.Config.set('Processor', 'mask', widget.mask_wid.text)
        self.Config.set('Processor', 'mode_prc', widget.proc_wid.text)
        self.Config.set('Processor', 'dyn_dark', widget.dark_wid.text)
        self.Config.set('Processor', 'blr_strength', self.blr_strength)
        self.Config.set('Processor', 'stack_size', widget.stack_wid.value)
        self.Config.set('Processor', 'ind_zoom', widget.indzoom_wid.value)
        self.Config.set('Processor', 'dout', widget.dout_wid.state)
        self.Config.set('Processor', 'vectype', widget.vectype_wid.text)
        self.Config.set('Processor', 'actuator', widget.actuator_wid.state)
        self.Config.set('Processor', 'actuator_class', self.actuator_class)
        self.Config.set('Processor', 'actuator_parm', self.actuator_parm)
        self.Config.set('Processor', 'override', widget.override_wid.state)

        # Section 'Output'
        self.Config.set('Output', 'output', widget.out_wid.state)
        self.Config.set('Output', 'output_dir', self.output_dir)
        self.Config.set('Output', 'recorder', widget.recorder_wid.text)
        self.Config.set('Output', 'blr_out', widget.oblur_wid.state)
        self.Config.set('Output', 'equ_out', widget.oequ_wid.text)
        self.Config.set('Output', 'dnz_out', widget.odnz_wid.state)
        self.Config.set('Output', 'dnz_out_str', self.dnz_out_str)
        self.Config.set('Output', 'flt_out', widget.oflt_wid.text)
        self.Config.set('Output', 'flt_out_strength', self.flt_out_strength)
        self.Config.set('Output', 'stb_out', widget.ostab_wid.state)
        self.Config.set('Output', 'gain_out', widget.ogain_wid.value)
        self.Config.set('Output', 'offset_out', widget.ooffset_wid.value)
        self.Config.set('Output', 'color_mode', widget.colors_wid.text)
        self.Config.set('Output', 'background_source', self.background_source)
        self.Config.set('Output', 'osd', widget.osd_wid.state)
        self.Config.set('Output', 'hud', widget.vec_wid.state)
        self.Config.set('Output', 'trf_mode', widget.trf_wid.text)
        self.Config.set('Output', 'trf_trig', self.trtrigger)
        self.Config.read(filename)
        self.Config.write()

    def read_parms(self, filename):
        if os.path.isfile(filename):
            self.Config.read(filename)
            # Section 'Input'
            self.video_src = self.Config.get('Input', 'video_src')
            self.video_width = int(self.Config.get('Input', 'video_width'))
            self.video_height = int(self.Config.get('Input', 'video_height'))
            self.prop_fourcc = self.Config.get('Input', 'video_codec')
            self.dnz_inp_str = float(self.Config.get('Input', 'dnz_inp_str'))
            self.flt_inp_strength = float(
                self.Config.get('Input', 'flt_inp_strength'))
            # Section 'Processor'
            self.blr_strength = int(
                self.Config.get('Processor', 'blr_strength'))
            self.actuator_class = self.Config.get('Processor',
                                                  'actuator_class')
            self.actuator_parm = self.Config.get('Processor', 'actuator_parm')
            # Section 'Output'
            self.output_dir = self.Config.get('Output', 'output_dir')
            self.dnz_out_str = float(self.Config.get('Output', 'dnz_out_str'))
            self.flt_out_strength = float(
                self.Config.get('Output', 'flt_out_strength'))
            self.background_source = self.Config.get('Output',
                                                     'background_source')
            self.trtrigger = self.Config.get('Output', 'trf_trig')
        else:
            print('File ' + str(filename) + ' does not exist.')

    def read_ui_parms(self, filename, widget):
        if os.path.isfile(filename):
            self.Config.read(filename)
            # Section 'Input'
            widget.playmode_wid.text = self.Config.get('Input', 'play_mode')
            widget.inp_wid.state = self.Config.get('Input', 'input')
            widget.flipx_wid.state = self.Config.get('Input', 'flip_x')
            widget.flipy_wid.state = self.Config.get('Input', 'flip_y')
            widget.iblur_wid.state = self.Config.get('Input', 'blr_inp')
            widget.iequ_wid.text = self.Config.get('Input', 'equ_inp')
            widget.idnz_wid.state = self.Config.get('Input', 'dnz_inp')
            widget.iflt_wid.text = self.Config.get('Input', 'flt_inp')
            widget.istab_wid.state = self.Config.get('Input', 'stb_inp')
            widget.igain_wid.value = float(self.Config.get(
                'Input', 'gain_inp'))
            widget.ioffset_wid.value = float(
                self.Config.get('Input', 'offset_inp'))
            widget.ichan_wid.text = self.Config.get('Input', 'color_channel')
            # Section 'Processor'
            widget.mask_wid.text = self.Config.get('Processor', 'mask')
            widget.proc_wid.text = self.Config.get('Processor', 'mode_prc')
            widget.dark_wid.text = self.Config.get('Processor', 'dyn_dark')
            widget.vectype_wid.text = self.Config.get('Processor', 'vectype')
            widget.stack_wid.value = int(
                self.Config.get('Processor', 'stack_size'))
            widget.indzoom_wid.value = float(
                self.Config.get('Processor', 'ind_zoom'))
            widget.dout_wid.state = self.Config.get('Processor', 'dout')
            widget.actuator_wid.state = self.Config.get(
                'Processor', 'actuator')
            widget.override_wid.state = self.Config.get(
                'Processor', 'override')
            # Section 'Output'
            widget.out_wid.state = self.Config.get('Output', 'output')
            widget.recorder_wid.text = self.Config.get('Output', 'recorder')
            widget.oblur_wid.state = self.Config.get('Output', 'blr_out')
            widget.oequ_wid.text = self.Config.get('Output', 'equ_out')
            widget.odnz_wid.state = self.Config.get('Output', 'dnz_out')
            widget.oflt_wid.text = self.Config.get('Output', 'flt_out')
            widget.ostab_wid.state = self.Config.get('Output', 'stb_out')
            widget.ogain_wid.value = float(
                self.Config.get('Output', 'gain_out'))
            widget.ooffset_wid.value = float(
                self.Config.get('Output', 'offset_out'))
            widget.colors_wid.text = self.Config.get('Output', 'color_mode')
            widget.osd_wid.state = self.Config.get('Output', 'osd')
            widget.vec_wid.state = self.Config.get('Output', 'hud')
            widget.trf_wid.text = self.Config.get('Output', 'trf_mode')

        else:
            print('File ' + str(filename) + ' does not exist.')
Ejemplo n.º 9
0
class cBaseScript(object):
    ''' basic script class to inherit all scrpts from '''
    def __init__(self):
        self.bIsInit                = False
        self.uMyPath                = u''
        self.uScriptName            = u''
        self.uScriptFile            = u''
        self.iMyVersion             = ToIntVersion('1.0.0')
        self.fOrcaVersion           = ToIntVersion('1.0.0')
        self.uType                  = u'Generic'
        self.uSubType               = u'Generic'
        self.aScriptIniSettings     = QueryDict()
        self.oConfigParser          = KivyConfigParser()
        self.uDefaultConfigName     = ""
        self.uConfigFileName        = ""
        self.uSection               = ""

    def RunScript(self, args):
        ''' Dummy '''
        pass

    def Init(self,oParORCA,uScriptName,uScriptFile):
        ''' Initializes the script '''
        self.bIsInit            = True
        self.uScriptName        = uScriptName
        self.uScriptFile        = uScriptFile
        self.uDefaultConfigName = uScriptName

        self.uMyPath            = AdjustPathToOs(oORCA.uScriptsPath+'/'+self.uScriptName)
        if not os.path.exists(self.uMyPath):
            CreateDir(self.uMyPath)
        oORCA.oTheScreen.oLanguage.LoadXmlFile("SCRIPT", uScriptName)

        self.uConfigFileName    = AdjustPathToOs(self.uMyPath+u'/config.ini')
        oRepManagerEntry=cRepManagerEntry()
        oRepManagerEntry.uFileName=uScriptFile
        if oRepManagerEntry.ParseFromSourceFile():
            self.iMyVersion     = oRepManagerEntry.oRepEntry.iVersion
            self.fOrcaVersion   = oRepManagerEntry.oRepEntry.iMinOrcaVersion
            #OrcaVersion defines for what Orca Version the Interface has been developed

        self.ShowDebug(u'Init')
        if not FileExists(self.uConfigFileName):
            self.CreateAndInitializeIniFile()

        oRepManagerEntry=cRepManagerEntry()
        oRepManagerEntry.uFileName=uScriptFile
        if oRepManagerEntry.ParseFromSourceFile():
            self.iMyVersion     = oRepManagerEntry.oRepEntry.iVersion
            self.fOrcaVersion   = oRepManagerEntry.oRepEntry.iMinOrcaVersion
            #OrcaVersion defines for what Orca Version the Script has been developed
        self.ReadConfigFromIniFile(self.uDefaultConfigName)

    def InitializeSection(self,uSection):
        ''' Initializes a section in the config.ini file for the script '''
        self.ReadConfigFromIniFile(uSection)
    def CreateAndInitializeIniFile(self):
        ''' Creates the ini file '''
        self.oConfigParser.add_section(self.uDefaultConfigName)
        self.InitializeSection(self.uDefaultConfigName)
        self.oConfigParser.write()
    def LoadConfig(self):
        ''' loads a config from the ini file '''
        self.oConfigParser.filename=self.uConfigFileName
        if len(self.oConfigParser._sections)==0:
            if FileExists(self.uConfigFileName):
                self.ShowDebug(u'Reading Config File')
                self.oConfigParser.read(self.uConfigFileName)
    def GetConfigJSONStringforSection(self,uSection):
        ''' dummy '''
        return u'{}'

    def ReadConfigFromIniFile(self,uConfigName):
        ''' reads a config from the ini file '''
        self.uSection = uConfigName

        try:
            SetVar('ScriptConfigSection',uConfigName)
            self.LoadConfig()
            oIniDef = json.loads(self.GetConfigJSONStringforSection(uConfigName))

            for oLine in oIniDef:
                uType       = oLine.get("type")
                uKey        = oLine.get("key")
                uDefault    = oLine.get("default")

                if uType == "scrolloptions" or uType == "string":
                    uPre = "u" + uKey
                    self.aScriptIniSettings[uPre]=Config_getdefault(self.oConfigParser,self.uSection, uKey,uDefault)
                elif uType == "numeric" or uType == "numericslider":
                    uPre= "i" + uKey
                    self.aScriptIniSettings[uPre]=ToInt(Config_getdefault(self.oConfigParser,self.uSection, uKey,uDefault))
                elif uType == "numericfloat" :
                    uPre= "f" + uKey
                    self.aScriptIniSettings[uPre]=ToFloat(Config_getdefault(self.oConfigParser,self.uSection, uKey,uDefault))
                elif uType == "bool":
                    uPre = "b" + uKey
                    self.aScriptIniSettings[uPre]=ToBool(Config_getdefault(self.oConfigParser,self.uSection, uKey,uDefault))
                elif uType == "title":
                    pass
                else:
                    self.ShowError(u'Cannot read config name (base), wrong attribute:'+self.uConfigFileName + u' Section:'+self.uSection+" " +oLine["type"])

        except Exception as e:
            self.ShowError(u'Cannot read config name (base):'+self.uConfigFileName + u' Section:'+self.uSection,e)
            return

    def DeInit(self):
        ''' deinitializes the ini file '''
        self.ShowDebug(u'DeInit')
    def OnPause(self):
        ''' called by system, if the device goes on pause '''
        self.ShowInfo(u'OnPause')
    def OnResume(self):
        ''' called by system, if the device resumes '''
        self.ShowInfo(u'OnResume')

    def ShowWarning(self,uMsg):
        ''' creates a warning debug line '''
        uRet=u'Script '+self.uScriptName+u': '+ uMsg
        Logger.warning (uRet)
        return uRet

    def ShowDebug(self,uMsg):
        ''' creates a debug line '''
        uRet=u'Script '+self.uScriptName+u': '+ uMsg
        Logger.debug (uRet)
        return uRet

    def ShowInfo(self,uMsg):
        ''' creates a info debug line '''
        uRet=u'Script '+self.uScriptName+u': '+ uMsg
        Logger.info (uRet)
        return uRet

    def ShowError(self,uMsg,oException=None):
        ''' creates a error debug line '''
        iErrNo = 0
        if oException!=None:
            if hasattr(oException,'errno'):
                iErrNo=oException.errno
        if iErrNo is None:
            iErrNo=12345

        uRet=LogErrorSmall (u'Script '+self.uScriptName+u': '+ uMsg + " (%d) " % (iErrNo),oException)
        return uRet

    def _ReadConfig(self):
        ''' reads the config for the settings dialog '''
        oConfig = KivyConfigParser()
        oConfig.read(self.uConfigFileName)
        return oConfig

    def ConfigScriptSettings(self,oScriptSetting):
        ''' for here we need a separate config object '''
        self.oConfigParser=self._ReadConfig()
        oScriptSetting.register_type('buttons'               , SettingButtons)
        oScriptSetting.register_type('numericslider'         , SettingNumericSlider)
        oScriptSetting.register_type('numericfloat'          , SettingNumeric)
        oScriptSetting.register_type('scrolloptions'         , SettingScrollOptions)

        SetVar('ScriptConfigSection',self.uDefaultConfigName)
        uSettingsJSON=self.GetConfigJSONStringforSection(self.uDefaultConfigName)
        self.ReadConfigFromIniFile(self.uDefaultConfigName)
        if uSettingsJSON==u'{}':
            return self.On_SettingsClose(None)
        uSettingsJSON=ReplaceVars(uSettingsJSON)
        oScriptSetting.add_json_panel(self.uDefaultConfigName,self.oConfigParser, data=uSettingsJSON)
        oScriptSetting.bind(on_close=self.On_SettingsClose)

        return oScriptSetting

    def On_SettingsClose(self,instance):
        ''' Dispatched when the user closes the settings dialog '''
        oORCA.DispatchSystemKey('buttonclosesetting_script')
        return True

    def ShowSettings(self):
        '''  shows the settings dialog '''
        oORCA.oTheScreen.AddActionToQueue([{'string':'updatewidget','widgetname':'Scriptsettings'}])
Ejemplo n.º 10
0
class cScriptConfig(object):
    """ Class to manage the initialisation/configuration and access the the settings of an Script settings objects

    """
    def __init__(self, oScript):
        self.oScript = oScript
        self.oConfigParser = KivyConfigParser()
        self.oFnConfig = None
        self.uCurrentSection = None
        self.uDefaultConfigName = u'SCRIPTDEFAULT'
        self.aDiscoverScriptList = None
        self.oInputKeyboard = None
        self.dDefaultSettings = {
            "SettingTitle": {
                "active": "enabled",
                "order": 0,
                "type": "title",
                "title": "$lvar(560)"
            },
            "TimeOut": {
                "active": "disabled",
                "order": 1,
                "type": "numericfloat",
                "title": "$lvar(6019)",
                "desc": "$lvar(6020)",
                "section": "$var(ScriptConfigSection)",
                "key": "TimeOut",
                "default": "1.0"
            },
            "Host": {
                "active": "disabled",
                "order": 5,
                "type": "string",
                "title": "$lvar(6004)",
                "desc": "$lvar(6005)",
                "section": "$var(ScriptConfigSection)",
                "key": "Host",
                "default": "192.168.1.2"
            },
            "Port": {
                "active": "disabled",
                "order": 6,
                "type": "string",
                "title": "$lvar(6002)",
                "desc": "$lvar(6003)",
                "section": "$var(ScriptConfigSection)",
                "key": "Port",
                "default": "80"
            },
            "User": {
                "active": "disabled",
                "order": 7,
                "type": "string",
                "title": "$lvar(6006)",
                "desc": "$lvar(6007)",
                "section": "$var(ScriptConfigSection)",
                "key": "User",
                "default": ""
            },
            "Password": {
                "active": "disabled",
                "order": 8,
                "type": "string",
                "title": "$lvar(6008)",
                "desc": "$lvar(6009)",
                "section": "$var(ScriptConfigSection)",
                "key": "Password",
                "default": ""
            },
            "ConfigChangeButtons": {
                "active":
                "disabled",
                "order":
                999,
                "type":
                "buttons",
                "title":
                "$lvar(565)",
                "desc":
                "$lvar(566)",
                "section":
                "$var(ScriptConfigSection)",
                "key":
                "configchangebuttons",
                "buttons": [{
                    "title": "$lvar(569)",
                    "id": "button_add"
                }, {
                    "title": "$lvar(570)",
                    "id": "button_delete"
                }, {
                    "title": "$lvar(571)",
                    "id": "button_rename"
                }]
            },
        }

        self.dSettingsCombined = {}

    def Init(self):
        """ Init function, sets the configuration file name and add the default sections """

        self.oFnConfig = cFileName(self.oScript.oPathMy) + u'config.ini'
        if not self.oFnConfig.Exists():
            self.oConfigParser.filename = self.oFnConfig.string
            self.CreateSection(uSectionName=self.uDefaultConfigName)

    def LoadConfig(self):
        """ Loads the config file (only once) """

        try:
            self.oConfigParser.filename = self.oFnConfig.string
            if len(self.oConfigParser._sections) == 0:
                if self.oFnConfig.Exists():
                    self.oScript.ShowDebug(u'Reading Config File')
                    self.oConfigParser.read(self.oFnConfig.string)
        except Exception as e:
            self.oScript.ShowError(
                u"can\'t load config file: %s" % self.oFnConfig.string, None,
                e)

    def CreateSection(self, uSectionName):
        """
        Adds a new section to the config parser

        :param string uSectionName: The name of the section to create
        """
        self.oScript.ShowDebug('Adding new section [%s]' % (uSectionName))
        self.oConfigParser.add_section(uSectionName)
        self.oConfigParser.write()

    def GetSettingParFromIni(self, uSectionName, uVarName):
        """
        Returns a setting for the configuration ini file
        If the entry does not exist, it tries to puls the value from the  aInterFaceIniSettings dict of already predifined settings
        If not exist there as well, an error will be logged

        :rtype: string|None
        :param string uSectionName: The name of the section
        :param uVarName: The name of the parameter/setting in the section
        :return: The value of the setting, empty string if not found
         """

        oSetting = self.oScript.GetSettingObjectForConfigName(uSectionName)
        uResult = Config_GetDefault_Str(self.oConfigParser, uSectionName,
                                        uVarName, None)
        if uResult is None:
            uResult = str(oSetting.aScriptIniSettings.queryget(uVarName))
        if uResult is None:
            uResult = ''
            self.oScript.ShowError(u'can\'t find script setting: %s:%s' %
                                   (uSectionName, uVarName))
        else:
            self.oScript.ShowDebug(u'Returning script setting: %s from %s:%s' %
                                   (uResult, uSectionName, uVarName))
        return uResult

    def WriteDefinitionConfigPar(self,
                                 uSectionName,
                                 uVarName,
                                 uVarValue,
                                 bNowrite=False,
                                 bForce=False):
        """ Writes a variable to the config file
        :param string uSectionName: The name of the section
        :param string uVarName: The name of the parameter/setting in the section
        :param string uVarValue: The value for the setting
        :param bool bNowrite: Flag, if we should not immidiatly write the the setting
        :param bool bForce: Flag to force write, even if parameter exists in config
        """
        self.LoadConfig()
        if not self.oConfigParser.has_section(uSectionName):
            self.CreateSection(uSectionName=uSectionName)

        if self.oConfigParser.has_option(uSectionName, uVarName):
            if not bForce:
                return

        self.oConfigParser.set(uSectionName, uVarName, uVarValue)
        if not bNowrite:
            self.oConfigParser.write()

        for uSettingName in self.oScript.aSettings:
            oSetting = self.oScript.aSettings[uSettingName]
            if oSetting.uConfigName == uSectionName:
                oSetting.aScriptIniSettings[uVarName] = uVarValue
                break

    def WriteDefinitionConfig(self, uSectionName, dSettings):
        """
        writes all vars given in a dictionary to the config file

        :param string uSectionName: The name of the section
        :param dict dSettings: A dict of all settings to write
        """

        for uKey in dSettings:
            self.WriteDefinitionConfigPar(uSectionName=uSectionName,
                                          uVarName=uKey,
                                          uVarValue=dSettings[uKey],
                                          bNowrite=True)
        self.oConfigParser.write()

    def ConfigureKivySettings(self, oKivySetting):
        """
        Create the JSON string for all sections and applies it to a kivy settings object
        Discover settings are excluded

        :param setting oKivySetting:
        :return: The KivySetting object
        """
        RegisterSettingTypes(oKivySetting)
        aSections = self.oConfigParser.sections()
        if len(aSections) == 0:
            self.CreateSection(uSectionName=self.uDefaultConfigName)

        for uSection in aSections:
            # the Section list should be applied as a orca var
            SetVar(uVarName=u'ScriptConfigSection', oVarValue=uSection)
            # Let create a new temporary cSetting object to not harm the existing ones
            oSetting = self.oScript.cScriptSettings(self.oScript)
            # Read the ini file for this section
            oSetting.ReadConfigFromIniFile(uSection)
            # Create the setting string
            dSettingsJSON = self.CreateSettingJsonCombined(oSetting=oSetting)
            uSettingsJSON = SettingDictToString(dSettingsJSON)
            uSettingsJSON = ReplaceVars(uSettingsJSON)
            oSetting = None

            # if there is nothing to configure, then return
            if uSettingsJSON == u'{}':
                Globals.oNotifications.SendNotification('closesetting_script')
                return False

            # add the jSon to the Kivy Setting
            oKivySetting.add_json_panel(uSection,
                                        self.oConfigParser,
                                        data=uSettingsJSON)

        # Adds the action handler
        oKivySetting.bind(on_config_change=self.On_ConfigChange)
        return oKivySetting

    def On_ConfigChange(self, oSettings, oConfig, uSection, uKey, uValue):
        """ reacts, if user changes a setting """
        if uKey == u'configchangebuttons':
            self.uCurrentSection = uSection
            if uValue == u'button_add':
                SetVar(uVarName=u'SCRIPTINPUT', oVarValue=u'DEVICE_dummy')
                self.oInputKeyboard = ShowKeyBoard(u'SCRIPTINPUT',
                                                   self.On_InputAdd)
            if uValue == u'button_delete':
                ShowQuestionPopUp(
                    uTitle=u'$lvar(5003)',
                    uMessage=u'Do you really want to delete this setting?',
                    fktYes=self.On_InputDel,
                    uStringYes=u'$lvar(5001)',
                    uStringNo=u'$lvar(5002)')
            if uValue == u'button_rename':
                SetVar(uVarName=u'SCRIPTINPUT', oVarValue=uSection)
                self.oInputKeyboard = ShowKeyBoard(u'SCRIPTINPUT',
                                                   self.On_InputRen)
        else:
            oSetting = self.oScript.GetSettingObjectForConfigName(
                uConfigName=uSection)
            oSetting.aScriptIniSettings[uKey] = uValue

    def On_InputAdd(self, uInput):
        """ User pressed the add configuration button """
        if uInput == u'':
            return
        if self.oConfigParser.has_section(uInput):
            return
        self.oConfigParser.add_section(uInput)
        # self.InitializeSection(uInput)
        self.oConfigParser.write()
        Globals.oTheScreen.AddActionToQueue([{
            'string': 'updatewidget',
            'widgetname': 'Scriptsettings'
        }])
        self.ShowSettings()

    def On_InputDel(self):
        """ User pressed the del configuration button """
        self.oConfigParser.remove_section(self.uCurrentSection)
        self.oConfigParser.write()
        self.ShowSettings()

    def On_InputRen(self, uInput):
        """ User pressed the rename configuration button """
        if uInput == u'':
            return
        if self.oConfigParser.has_section(uInput):
            return
        self.oConfigParser._sections[uInput] = self.oConfigParser._sections[
            self.uCurrentSection]
        self.oConfigParser._sections.pop(self.uCurrentSection)
        self.oConfigParser.write()
        self.ShowSettings()

    def ShowSettings(self):
        """ Shows the settings page """
        Globals.oTheScreen.AddActionToQueue([{
            'string': 'updatewidget',
            'widgetname': 'Scriptsettings'
        }])

    def GetSettingParFromVar2(self, uScriptName, uConfigName, uSettingParName):
        """
        Gets a Value for a setting parameter from the orca vars
        The Orca vars fpr the parameter are automatically set in the cInterfaceMonitoredSettings class

        :rtype: string
        :param uScriptName: The name of script to use
        :param uConfigName: The nemae of the Config
        :param uSettingParName: The name of the parameter
        :return: The value of the parameter
        """

        return GetVar(uVarName="CONFIG_" + uSettingParName.upper(),
                      uContext=uScriptName + u'/' + uConfigName)

    def CreateSettingJsonCombined(self, oSetting):
        """
        Creates a json dict which holds all the setting defintions of
        the core interface plus the settinmgs from the discover script (if requested)

        :rtype: dict
        :param cBaseInterFaceSettings oSetting: an IterFaceSettins Object
        :return: a dict of combined settings
        """

        if len(self.dSettingsCombined) != 0:
            return self.dSettingsCombined
        dRet = {}

        for uKey in self.dDefaultSettings:
            if self.dDefaultSettings[uKey]["active"] != "disabled":
                dRet[uKey] = self.dDefaultSettings[uKey]

        dScriptJSON = self.oScript.GetConfigJSON()
        for uKey in dScriptJSON:
            dLine = dScriptJSON[uKey]
            iOrder = dLine['order']
            for uKey2 in dRet:
                if dRet[uKey2]['order'] >= iOrder:
                    dRet[uKey2]['order'] += 1
            dRet[uKey] = dLine

        self.dSettingsCombined = dRet
        return dRet
Ejemplo n.º 11
0
playerID=
name=
localhost=False
master=False

[graphics]
width={}
height={}
fullscreen=

""".format(*defaultWindowSize)

if not path.isfile(cfgFile):
    with open(cfgFile, mode="w") as config:
        config.write(defaultCfg)

rboCfg = ConfigParser(name="rboclient")

for section in ["fields", "graphics"]:
    rboCfg.add_section(section)

rboCfg.read(cfgFile)

import kivy.resources  # noqa E402

from rboclient.gui.app import ClientApp  # noqa E402

kivy.resources.resource_add_path("rboclient/kv")

ClientApp(rboCfg, defaultWindowSize).run()
Ejemplo n.º 12
0
class cInterFaceConfig(object):
    """ Class to manage the initialisation/configuration and access toe the settings of an Interface settings objects

    """
    def __init__(self, oInterFace):
        self.oInterFace = oInterFace
        self.oConfigParser = KivyConfigParser()
        self.oFnConfig = None
        self.uCurrentSection = None
        self.uDefaultConfigName = u'DEVICE_DEFAULT'
        self.aDiscoverScriptList = None
        self.oInputKeyboard = None
        self.dDefaultSettings = {
            "SettingTitle": {
                "active": "enabled",
                "order": 0,
                "type": "title",
                "title": "$lvar(560)"
            },
            "Host": {
                "active": "disabled",
                "order": 1,
                "type": "string",
                "title": "$lvar(6004)",
                "desc": "$lvar(6005)",
                "section": "$var(InterfaceConfigSection)",
                "key": "Host",
                "default": "192.168.1.2"
            },
            "Port": {
                "active": "disabled",
                "order": 2,
                "type": "string",
                "title": "$lvar(6002)",
                "desc": "$lvar(6003)",
                "section": "$var(InterfaceConfigSection)",
                "key": "Port",
                "default": "80"
            },
            "User": {
                "active": "disabled",
                "order": 3,
                "type": "string",
                "title": "$lvar(6006)",
                "desc": "$lvar(6007)",
                "section": "$var(InterfaceConfigSection)",
                "key": "User",
                "default": "root"
            },
            "Password": {
                "active": "disabled",
                "order": 4,
                "type": "string",
                "title": "$lvar(6008)",
                "desc": "$lvar(6009)",
                "section": "$var(InterfaceConfigSection)",
                "key": "Password",
                "default": ""
            },
            "FNCodeset": {
                "active": "disabled",
                "order": 5,
                "type": "scrolloptions",
                "title": "$lvar(6000)",
                "desc": "$lvar(6001)",
                "section": "$var(InterfaceConfigSection)",
                "key": "FNCodeset",
                "default": "Select",
                "options": ["$var(InterfaceCodesetList)"]
            },
            "ParseResult": {
                "active": "disabled",
                "order": 6,
                "type": "scrolloptions",
                "title": "$lvar(6027)",
                "desc": "$lvar(6028)",
                "section": "$var(InterfaceConfigSection)",
                "key": "ParseResult",
                "default": "store",
                "options": ["no", "tokenize", "store", "json", "dict", "xml"]
            },
            "TokenizeString": {
                "active": "disabled",
                "order": 7,
                "type": "string",
                "title": "$lvar(6029)",
                "desc": "$lvar(6030)",
                "section": "$var(InterfaceConfigSection)",
                "key": "TokenizeString",
                "default": ":"
            },
            "TimeOut": {
                "active": "disabled",
                "order": 8,
                "type": "numericfloat",
                "title": "$lvar(6019)",
                "desc": "$lvar(6020)",
                "section": "$var(InterfaceConfigSection)",
                "key": "TimeOut",
                "default": "1.0"
            },
            "TimeToClose": {
                "active": "disabled",
                "order": 9,
                "type": "numeric",
                "title": "$lvar(6010)",
                "desc": "$lvar(6011)",
                "section": "$var(InterfaceConfigSection)",
                "key": "TimeToClose",
                "default": "10"
            },
            "DisableInterFaceOnError": {
                "active": "disabled",
                "order": 10,
                "type": "bool",
                "title": "$lvar(529)",
                "desc": "$lvar(530)",
                "section": "$var(InterfaceConfigSection)",
                "key": "DisableInterFaceOnError",
                "default": "0"
            },
            "DisconnectInterFaceOnSleep": {
                "active": "disabled",
                "order": 11,
                "type": "bool",
                "title": "$lvar(533)",
                "desc": "$lvar(534)",
                "section": "$var(InterfaceConfigSection)",
                "key": "DisconnectInterFaceOnSleep",
                "default": "1"
            },
            "DiscoverSettingButton": {
                "active":
                "disabled",
                "order":
                12,
                "type":
                "buttons",
                "title":
                "$lvar(6033)",
                "desc":
                "$lvar(6034)",
                "section":
                "$var(InterfaceConfigSection)",
                "key":
                "DiscoverSettings",
                "buttons": [{
                    "title": "Discover Settings",
                    "id": "button_discover"
                }]
            },
            "ConfigChangeButtons": {
                "active":
                "enabled",
                "order":
                999,
                "type":
                "buttons",
                "title":
                "$lvar(565)",
                "desc":
                "$lvar(566)",
                "section":
                "$var(InterfaceConfigSection)",
                "key":
                "configchangebuttons",
                "buttons": [{
                    "title": "$lvar(569)",
                    "id": "button_add"
                }, {
                    "title": "$lvar(570)",
                    "id": "button_delete"
                }, {
                    "title": "$lvar(571)",
                    "id": "button_rename"
                }]
            }
        }

        self.dGenericDiscoverSettings = {
            "DiscoverScriptName": {
                "active": "hidden",
                "order": 100,
                "scriptsection": "$lvar(539)",
                "type": "scrolloptions",
                "title": "$lvar(6035)",
                "desc": "$lvar(6036)",
                "section": "$var(InterfaceConfigSection)",
                "key": "DiscoverScriptName",
                "default": "",
                "options": ["$var(DISCOVERSCRIPTLIST)"]
            },
            "SaveDiscoveredIP": {
                "active": "hidden",
                "order": 101,
                "scriptsection": "$lvar(539)",
                "type": "bool",
                "title": "$lvar(6031)",
                "desc": "$lvar(6032)",
                "section": "$var(InterfaceConfigSection)",
                "key": "SaveDiscoveredIP",
                "default": "1"
            },
            "OldDiscoveredIP": {
                "active": "hidden",
                "order": 102,
                "scriptsection": "$lvar(539)",
                "type": "string",
                "title": "$lvar(6021)",
                "desc": "$lvar(6022)",
                "section": "$var(InterfaceConfigSection)",
                "key": "OldDiscoveredIP",
                "default": ""
            },
            "CheckDiscoverButton": {
                "active":
                "disabled",
                "order":
                103,
                "scriptsection":
                "$lvar(539)",
                "type":
                "buttons",
                "title":
                "Check Discover",
                "desc":
                "$lvar(6034)",
                "section":
                "$var(InterfaceConfigSection)",
                "key":
                "CheckDiscover",
                "buttons": [{
                    "title": "Check Discover",
                    "id": "button_checkdiscover"
                }]
            },
        }
        self.dSettingsCombined = {}

    def Init(self):
        """ Init function, sets the configuration file name and add the default sections """

        self.oFnConfig = cFileName(self.oInterFace.oPathMy) + u'config.ini'
        if not self.oFnConfig.Exists():
            self.CreateSection(uSectionName=self.uDefaultConfigName)

    def LoadConfig(self):
        """ Loads the config file (only once) """

        try:
            self.oConfigParser.filename = self.oFnConfig.string
            if len(self.oConfigParser._sections) == 0:
                if self.oFnConfig.Exists():
                    self.oInterFace.ShowDebug(u'Reading Config File')
                    self.oConfigParser.read(self.oFnConfig.string)
            else:
                if not self.oFnConfig.Exists():
                    self.oConfigParser.write()
        except Exception as e:
            self.oInterFace.ShowError(
                u"can\'t load config file: %s" % self.oFnConfig.string, None,
                e)

    def CreateSection(self, uSectionName):
        """
        Adds a new section to the config parser

        :param string uSectionName: The name of the section to create
        """

        self.oInterFace.ShowDebug('Adding new section [%s]' % (uSectionName))
        self.oConfigParser.add_section(uSectionName)
        self.oConfigParser.write()

    def GetSettingParFromIni(self, uSectionName, uVarName):
        """
        Returns a setting for the configuration ini file
        If the entry does not exist, it tries to puls the value from the  aInterFaceIniSettings dict of already predifined settings
        If not exist there as well, an error will be logged

        :rtype: string|None
        :param string uSectionName: The name of the section
        :param uVarName: The name of the parameter/setting in the section
        :return: The value of the setting, empty string if not found
         """

        oSetting = self.oInterFace.GetSettingObjectForConfigName(uSectionName)
        uResult = Config_GetDefault_Str(self.oConfigParser, uSectionName,
                                        uVarName, None)
        if uResult is None:
            uResult = str(oSetting.aInterFaceIniSettings.queryget(uVarName))
        if uResult is None:
            uResult = ''
            self.oInterFace.ShowError(u'can\'t find interface setting: %s:%s' %
                                      (uSectionName, uVarName))
        else:
            self.oInterFace.ShowDebug(
                u'Returning interface setting: %s from %s:%s' %
                (uResult, uSectionName, uVarName))
        return uResult

    def WriteDefinitionConfigPar(self,
                                 uSectionName,
                                 uVarName,
                                 uVarValue,
                                 bNowrite=False,
                                 bForce=False):
        """ Writes a variable to the config file
        :param string uSectionName: The name of the section
        :param string uVarName: The name of the parameter/setting in the section
        :param string uVarValue: The value for the setting
        :param bool bNowrite: Flag, if we should not immidiatly write the the setting
        :param bool bForce: Flag to force write, even if parameter exists in config
        """
        self.LoadConfig()
        if not self.oConfigParser.has_section(uSectionName):
            self.CreateSection(uSectionName=uSectionName)

        if self.oConfigParser.has_option(uSectionName, uVarName):
            if not bForce:
                return

        self.oConfigParser.set(uSectionName, uVarName, uVarValue)
        if not bNowrite:
            self.oConfigParser.write()

        for uSettingName in self.oInterFace.aSettings:
            oSetting = self.oInterFace.aSettings[uSettingName]
            if oSetting.uConfigName == uSectionName:
                oSetting.aInterFaceIniSettings[uVarName] = uVarValue
                break

    def WriteDefinitionConfig(self, uSectionName, dSettings):
        """
        writes all vars given in a dictionary to the config file

        :param string uSectionName: The name of the section
        :param dict dSettings: A dict of all settings to write
        """

        for uKey in dSettings:
            self.WriteDefinitionConfigPar(uSectionName=uSectionName,
                                          uVarName=uKey,
                                          uVarValue=dSettings[uKey],
                                          bNowrite=True)
        self.oConfigParser.write()

    def ConfigureKivySettings(self, oKivySetting):
        """
        Create the JSON string for all sections and applies it to a kivy settings object
        Discover settings are excluded

        :param setting oKivySetting:
        :return: The KivySetting object
        """
        RegisterSettingTypes(oKivySetting)
        aSections = self.oConfigParser.sections()
        if len(aSections) == 0:
            self.CreateSection(uSectionName=self.uDefaultConfigName)

        # The Codeset List could be applied as a orca var, so set it to the list
        SetVar(uVarName=u'InterfaceCodesetList',
               oVarValue=self.oInterFace.CreateCodsetListJSONString())

        for uSection in aSections:
            # the Section list should be applied as a orca var
            SetVar(uVarName=u'InterfaceConfigSection', oVarValue=uSection)
            # Let create a new temporary cSetting object to not harm the existing ones
            oSetting = self.oInterFace.cInterFaceSettings(self.oInterFace)
            # Read the ini file for this section
            oSetting.ReadConfigFromIniFile(uSection)
            # Create the setting string
            dSettingsJSON = self.CreateSettingJsonCombined(
                oSetting=oSetting, bIncludeDiscoverSettings=False)
            uSettingsJSON = SettingDictToString(dSettingsJSON)
            uSettingsJSON = ReplaceVars(uSettingsJSON)
            oSetting = None

            # if there is nothing to configure, then return
            if uSettingsJSON == u'{}':
                Globals.oNotifications.SendNotification(
                    'closesetting_interface')
                return False

            # add the jSon to the Kivy Setting
            oKivySetting.add_json_panel(uSection,
                                        self.oConfigParser,
                                        data=uSettingsJSON)

        # Adds the action handler
        oKivySetting.bind(on_config_change=self.On_ConfigChange)
        return oKivySetting

    def On_ConfigChange(self, oSettings, oConfig, uSection, uKey, uValue):
        """
        reacts, if user changes a setting

        :param setting oSettings: The kivy settings object
        :param ConfigParser oConfig: The Kivy config parser
        :param string uSection: The section of the change
        :param string uKey: The key name
        :param string uValue: The value
        """
        if uKey == u'configchangebuttons':
            self.uCurrentSection = uSection
            if uValue == u'button_add':
                SetVar(uVarName=u'INTERFACEINPUT', oVarValue=u'DEVICE_dummy')
                self.oInputKeyboard = ShowKeyBoard(u'INTERFACEINPUT',
                                                   self.On_InputAdd)
            if uValue == u'button_delete':
                ShowQuestionPopUp(
                    uTitle=u'$lvar(5003)',
                    uMessage=u'Do you really want to delete this setting?',
                    fktYes=self.On_InputDel,
                    uStringYes=u'$lvar(5001)',
                    uStringNo=u'$lvar(5002)')
            if uValue == u'button_rename':
                SetVar(uVarName=u'INTERFACEINPUT', oVarValue=uSection)
                self.oInputKeyboard = ShowKeyBoard(u'INTERFACEINPUT',
                                                   self.On_InputRen)
        elif uKey == u'DiscoverSettings':
            Globals.oTheScreen.uConfigToConfig = uSection
            Globals.oTheScreen.AddActionShowPageToQueue(
                uPageName=u'Page_InterfaceSettingsDiscover')
        elif uKey == u'FNCodeset':
            oSetting = self.oInterFace.GetSettingObjectForConfigName(
                uConfigName=uSection)
            oSetting.aInterFaceIniSettings[uKey] = uValue
            oSetting.ReadCodeset()
        else:
            oSetting = self.oInterFace.GetSettingObjectForConfigName(
                uConfigName=uSection)
            oSetting.aInterFaceIniSettings[uKey] = uValue
            # ShowMessagePopUp(uMessage=u'$lvar(5011)')
            if uKey == u'FNCodeset':
                oSetting.ReadCodeset()

    def On_InputAdd(self, uInput):
        """
        User pressed the add configuration button

        :param string uInput: The Name of the section
        :return:
        """
        if uInput == u'':
            return
        if self.oConfigParser.has_section(uInput):
            return
        self.oConfigParser.add_section(uInput)
        self.oConfigParser.write()
        Globals.oTheScreen.AddActionToQueue([{
            'string': 'updatewidget',
            'widgetname': 'Interfacesettings'
        }])
        self.ShowSettings()

    def On_InputDel(self):
        """ User pressed the del configuration button """
        self.oConfigParser.remove_section(self.uCurrentSection)
        self.oConfigParser.write()
        self.ShowSettings()

    def On_InputRen(self, uInput):
        """ User pressed the rename configuration button """
        if uInput == u'':
            return
        if self.oConfigParser.has_section(uInput):
            return
        self.oConfigParser._sections[uInput] = self.oConfigParser._sections[
            self.uCurrentSection]
        self.oConfigParser._sections.pop(self.uCurrentSection)
        self.oConfigParser.write()
        self.ShowSettings()

    def ShowSettings(self):
        """ Shows the settings page """
        Globals.oTheScreen.AddActionToQueue([{
            'string': 'updatewidget',
            'widgetname': 'Interfacesettings'
        }])

    def GetSettingParFromVar2(self, uInterFaceName, uConfigName,
                              uSettingParName):
        """
        Gets a Value for a setting parameter from the orca vars
        The Orca vars fpr the parameter are automatically set in the cInterfaceMonitoredSettings class

        :rtype: string
        :param uInterFaceName: The name of interface to use
        :param uConfigName: The nemae of the Config
        :param uSettingParName: The name of the parameter
        :return: The value of the parameter
        """

        return GetVar(uVarName="CONFIG_" + uSettingParName.upper(),
                      uContext=uInterFaceName + u'/' + uConfigName)

    def GetSettingParFromVar(self, uLink):
        """
        Returns a setting var of a an other interface or config
        The Interfca emust already be initalized
        syntax should be: linked:interfacename:configname:varname

        :rtype: string
        :param string uLink: The link: syntax should be: linked:interfacename:configname:varname
        :return: The Value of the linked setting, empty string, if not found
        """

        aLinks = uLink.split(':')
        if len(aLinks) == 4:
            uInterFaceName = aLinks[1]
            uConfigName = aLinks[2]
            uSettingParName = aLinks[3]
            Globals.oInterFaces.LoadInterface(uInterFaceName)
            oInterface = Globals.oInterFaces.GetInterface(uInterFaceName)
            oSetting = oInterface.GetSettingObjectForConfigName(
                uConfigName=uConfigName)
            oSetting.Discover()
            return self.GetSettingParFromVar2(uInterFaceName=uInterFaceName,
                                              uConfigName=uConfigName,
                                              uSettingParName=uSettingParName)
        return ""

    def CreateSettingJsonCombined(self,
                                  oSetting,
                                  bIncludeDiscoverSettings=True):
        """
        Creates a json dict which holds all the setting defintions of
        the core interface plus the settings from the discover script (if requested)

        :rtype: dict
        :param cBaseInterFaceSettings oSetting: an IterFaceSettins Object
        :param bool bIncludeDiscoverSettings: If we want to include the discover settings
        :return: a dict of combined settings
        """

        if len(self.dSettingsCombined) != 0:
            return self.dSettingsCombined
        dRet = {}

        for uKey in self.dDefaultSettings:
            if self.dDefaultSettings[uKey]["active"] != "disabled":
                dRet[uKey] = self.dDefaultSettings[uKey]

        dInterFaceJSON = self.oInterFace.GetConfigJSON()
        for uKey in dInterFaceJSON:
            dLine = dInterFaceJSON[uKey]
            iOrder = dLine['order']
            for uKey2 in dRet:
                if dRet[uKey2]['order'] >= iOrder:
                    dRet[uKey2]['order'] += 1
            dRet[uKey] = dLine

        if 'DiscoverSettingButton' in dRet and bIncludeDiscoverSettings:
            dRet.update(self.dGenericDiscoverSettings)
            if self.aDiscoverScriptList is None:
                self.aDiscoverScriptList = Globals.oScripts.GetScriptListForScriptType(
                    "DEVICE_DISCOVER")
            iLastOrder = 200
            for uDiscoverScriptName in self.aDiscoverScriptList:
                oScript = Globals.oScripts.LoadScript(uDiscoverScriptName)
                dScriptJSONSettings = oScript.cScript.GetConfigJSONforParameters(
                    oSetting.aInterFaceIniSettings)
                iMax = 0
                for uKey in dScriptJSONSettings:
                    uTempKey = uDiscoverScriptName + "_" + uKey
                    dRet[uTempKey] = dScriptJSONSettings[uKey]
                    dRet[uTempKey]['key'] = uDiscoverScriptName.upper(
                    ) + "_" + dScriptJSONSettings[uKey]['key']
                    dRet[uTempKey]['scriptsection'] = uDiscoverScriptName
                    dRet[uTempKey]['active'] = 'hidden'
                    iOrder = dRet[uTempKey]['order']
                    iMax = max(iMax, iOrder)
                    dRet[uTempKey]['order'] = iOrder + iLastOrder

                iLastOrder += iMax
        self.dSettingsCombined = dRet
        return dRet
Ejemplo n.º 13
0
class Settings:
    def __init__(self):
        self.Config = ConfigParser()
        self.Config.add_section('Input')
        self.Config.add_section('Processor')
        self.Config.add_section('Output')
        # default values
        self.cfgfilename = 'default.conf'
        self.helpfile = 'doc/PyFSPro_dataflow.jpg'
        self.numframes = 255  # No. of frames in stack
        self.color_mode = -1  # Greyscale output
        self.video_src = 0  # Default camera
        self.video_width = 1024
        self.video_height = 768
        self.show_inp = True
        self.show_out = True
        self.show_vec = False
        self.show_help = False

        # settings for video and image sequence recording
        self.recordi = False
        self.recordv = False
        self.novfile = True
        self.imgindx = 0
        self.output_path = './output/'
        self.image_dst = self.output_path
        self.video_dst = self.output_path

        # switches for image filters and tools
        self.blr_inp = False
        self.blr_out = False
        self.blr_strength = 7
        self.equ_inp = 0
        self.equ_out = 0
        self.dnz_inp = False
        self.dnz_out = False
        self.dnz_inp_str = 33
        self.dnz_out_str = 33
        self.flt_inp = 0
        self.flt_out = 0
        self.flt_inp_strength = 0
        self.flt_out_strength = 0
        self.flt_inp_kernel = None
        self.flt_out_kernel = None
        self.flip_x = False
        self.flip_y = False
        self.inp_kernel = None
        self.out_kernel = None
        #self.mode_in = 0
        self.mode_prc = 0
        #self.mode_out = 0
        self.pseudoc = False
        self.dyn_dark = True
        self.gain_inp = 1.0
        self.gain_out = 1.0
        self.offset_inp = 0
        self.offset_out = 0
        self.vec_zoom = 0.1
        self.loop = False
        self.stb_inp = False
        self.stb_out = False
        self.osd_txtline = 2
        self.green = (0, 255, 0)
        self.red = (0, 0, 255)
        self.blue = (255, 0, 0)
        self.black = (0, 0, 0)
        self.colormaps = [
            'AUTUMN', 'BONE', 'JET', 'WINTER', 'RAINBOW', 'OCEAN', 'SUMMER',
            'SPRING', 'COOL', 'HSV', 'PINK', 'HOT'
        ]
        self.set_defaults()

    def gettime(self):
        self.timestring = time.strftime("%Y%m%d-%H%M%S", time.gmtime())
        return self.timestring

    def set_defaults(self):
        # Section 'Input'
        self.Config.setdefault('Input', 'video_src', self.video_src)
        self.Config.setdefault('Input', 'video_width', self.video_width)
        self.Config.setdefault('Input', 'video_height', self.video_height)
        self.Config.setdefault('Input', 'loop', self.loop)
        self.Config.setdefault('Input', 'flip_x', self.flip_x)
        self.Config.setdefault('Input', 'flip_y', self.flip_y)
        self.Config.setdefault('Input', 'blr_inp', self.blr_inp)
        self.Config.setdefault('Input', 'equ_inp', self.equ_inp)
        self.Config.setdefault('Input', 'dnz_inp', self.dnz_inp)
        self.Config.setdefault('Input', 'dnz_inp_str', self.dnz_inp_str)
        self.Config.setdefault('Input', 'flt_inp', self.flt_inp)
        self.Config.setdefault('Input', 'flt_inp_strength',
                               self.flt_inp_strength)
        #self.Config.setdefault('Input','mode_in', self.mode_in)
        self.Config.setdefault('Input', 'gain_inp', self.gain_inp)
        self.Config.setdefault('Input', 'offset_inp', self.offset_inp)
        self.Config.setdefault('Input', 'stb_inp', self.stb_inp)

        # Section 'Processor'
        self.Config.setdefault('Processor', 'mode_prc', self.mode_prc)
        self.Config.setdefault('Processor', 'dyn_dark', self.dyn_dark)
        self.Config.setdefault('Processor', 'blr_strength', self.blr_strength)
        self.Config.setdefault('Processor', 'numframes', self.numframes)

        # Section 'Output'
        self.Config.setdefault('Output', 'video_dst', self.video_dst)
        self.Config.setdefault('Output', 'image_dst', self.image_dst)
        self.Config.setdefault('Output', 'recordv', self.recordv)
        self.Config.setdefault('Output', 'recordi', self.recordi)
        self.Config.setdefault('Output', 'blr_out', self.blr_out)
        self.Config.setdefault('Output', 'equ_out', self.equ_out)
        self.Config.setdefault('Output', 'dnz_out', self.dnz_out)
        self.Config.setdefault('Output', 'dnz_out_str', self.dnz_out_str)
        self.Config.setdefault('Output', 'flt_out', self.flt_out)
        self.Config.setdefault('Output', 'flt_out_strength',
                               self.flt_out_strength)
        #self.Config.setdefault('Output','mode_out', self.mode_out)
        self.Config.setdefault('Output', 'gain_out', self.gain_out)
        self.Config.setdefault('Output', 'offset_out', self.offset_out)
        self.Config.setdefault('Output', 'color_mode', self.color_mode)
        self.Config.setdefault('Output', 'pseudoc', self.pseudoc)
        self.Config.setdefault('Output', 'vec_zoom', self.vec_zoom)
        self.Config.setdefault('Output', 'stb_out', self.stb_out)

    def write_config(self, filename):
        if filename is None:
            filename = self.cfgfilename
        self.cfgfile = open(filename, 'w')

        # Section 'Input'
        self.Config.set('Input', 'video_src', self.video_src)
        self.Config.set('Input', 'video_width', self.video_width)
        self.Config.set('Input', 'video_height', self.video_height)
        self.Config.set('Input', 'loop', self.loop)
        self.Config.set('Input', 'flip_x', self.flip_x)
        self.Config.set('Input', 'flip_y', self.flip_y)
        self.Config.set('Input', 'blr_inp', self.blr_inp)
        self.Config.set('Input', 'equ_inp', self.equ_inp)
        self.Config.set('Input', 'dnz_inp', self.dnz_inp)
        self.Config.set('Input', 'dnz_inp_str', self.dnz_inp_str)
        self.Config.set('Input', 'flt_inp', self.flt_inp)
        self.Config.set('Input', 'flt_inp_strength', self.flt_inp_strength)
        #self.Config.set('Input','mode_in', self.mode_in)
        self.Config.set('Input', 'gain_inp', self.gain_inp)
        self.Config.set('Input', 'offset_inp', self.offset_inp)
        self.Config.set('Input', 'stb_inp', self.stb_inp)

        # Section 'Processor'
        self.Config.set('Processor', 'mode_prc', self.mode_prc)
        self.Config.set('Processor', 'dyn_dark', self.dyn_dark)
        self.Config.set('Processor', 'blr_strength', self.blr_strength)
        self.Config.set('Processor', 'numframes', self.numframes)

        # Section 'Output'
        self.Config.set('Output', 'video_dst', self.video_dst)
        self.Config.set('Output', 'image_dst', self.image_dst)
        self.Config.set('Output', 'recordv', self.recordv)
        self.Config.set('Output', 'recordi', self.recordi)
        self.Config.set('Output', 'blr_out', self.blr_out)
        self.Config.set('Output', 'equ_out', self.equ_out)
        self.Config.set('Output', 'dnz_out', self.dnz_out)
        self.Config.set('Output', 'dnz_out_str', self.dnz_out_str)
        self.Config.set('Output', 'flt_out', self.flt_out)
        self.Config.set('Output', 'flt_out_strength', self.flt_out_strength)
        #self.Config.set('Output','mode_out', self.mode_out)
        self.Config.set('Output', 'gain_out', self.gain_out)
        self.Config.set('Output', 'offset_out', self.offset_out)
        self.Config.set('Output', 'color_mode', self.color_mode)
        self.Config.set('Output', 'pseudoc', self.pseudoc)
        self.Config.set('Output', 'vec_zoom', self.vec_zoom)
        self.Config.set('Output', 'stb_out', self.stb_out)

        self.Config.write(self.cfgfile)
        self.cfgfile.close()

    def read_config(self, filename):
        if os.path.isfile(filename):
            self.Config.read(filename)
            self.video_src = self.Config.get('Input', 'video_src')
            self.video_width = int(self.Config.get('Input', 'video_width'))
            self.video_height = int(self.Config.get('Input', 'video_height'))
            self.loop = self.Config.getboolean('Input', 'loop')
            self.flip_x = self.Config.getboolean('Input', 'flip_x')
            self.flip_y = self.Config.getboolean('Input', 'flip_y')
            self.blr_inp = self.Config.getboolean('Input', 'blr_inp')
            self.equ_inp = int(self.Config.get('Input', 'equ_inp'))
            self.dnz_inp = self.Config.getboolean('Input', 'dnz_inp')
            self.dnz_inp_str = float(self.Config.get('Input', 'dnz_inp_str'))
            self.flt_inp = int(self.Config.get('Input', 'flt_inp'))
            self.flt_inp_strength = float(
                self.Config.get('Input', 'flt_inp_strength'))
            self.gain_inp = float(self.Config.get('Input', 'gain_inp'))
            self.offset_inp = float(self.Config.get('Input', 'offset_inp'))
            self.stb_inp = self.Config.getboolean('Input', 'stb_inp')
            self.mode_prc = int(self.Config.get('Processor', 'mode_prc'))
            self.dyn_dark = self.Config.getboolean('Processor', 'dyn_dark')
            self.blr_strength = int(
                self.Config.get('Processor', 'blr_strength'))
            self.numframes = int(self.Config.get('Processor', 'numframes'))
            self.video_dst = self.Config.get('Output', 'video_dst')
            self.image_dst = self.Config.get('Output', 'image_dst')
            self.recordv = self.Config.getboolean('Output', 'recordv')
            self.recordi = self.Config.getboolean('Output', 'recordi')
            self.blr_out = self.Config.getboolean('Output', 'blr_out')
            self.equ_out = int(self.Config.get('Output', 'equ_out'))
            self.dnz_out = self.Config.getboolean('Output', 'dnz_out')
            self.dnz_out_str = float(self.Config.get('Output', 'dnz_out_str'))
            self.flt_out = int(self.Config.get('Output', 'flt_out'))
            self.flt_out_strength = float(
                self.Config.get('Output', 'flt_out_strength'))
            self.gain_out = float(self.Config.get('Output', 'gain_out'))
            self.offset_out = float(self.Config.get('Output', 'offset_out'))
            self.color_mode = int(self.Config.get('Output', 'color_mode'))
            self.pseudoc = self.Config.getboolean('Output', 'pseudoc')
            self.vec_zoom = float(self.Config.get('Output', 'vec_zoom'))
            self.stb_out = self.Config.getboolean('Output', 'stb_out')
        else:
            print('File ' + str(filename) + ' does not exist.')