Python kivy 模块,config() 实例源码

我们从Python开源项目中,提取了以下34个代码示例,用于说明如何使用kivy.config()

项目:HeaTDV4A    作者:HeaTTheatR    | 项目源码 | 文件源码
def build(self):
        self.title = core.string_lang_title[:-1]  # ????????? ???? ?????????
        self.icon = "Data/Images/logo.png"  # ?????? ???? ?????????
        self.use_kivy_settings = False

        self.config = ConfigParser()
        self.config.read("{}/program.ini".format(core.prog_path))
        self.beep = SoundLoader.load("Data/mess_unread.wav")
        self.set_variable_from_settings()

        # ???????? ???????? ???????.
        self.start_screen = \
            StartScreen(name_buttons_menu=core.name_buttons_menu,
                        buttons_menu=core.buttons_menu,
                        buttons_group=core.buttons_group,
                        previous="Data/Images/logo.png",
                        title_previous=core.string_lang_title[:-1],
                        title_image="Data/Images/DV.png",
                        overflow_image="Data/Images/overflow_image.png",
                        previous_image="Data/Images/previous_image.png",
                        events_callback=self.events_program)
        self.screen = self.start_screen

        Clock.schedule_once(self.read_license, 3)
        return self.start_screen
项目:mobileinsight-mobile    作者:mobile-insight    | 项目源码 | 文件源码
def create_app_default_config(self, config):
        app_list = get_plugins_list()
        for app in app_list:
            APP_NAME = app
            APP_DIR = app_list[app][0]
            setting_path = os.path.join(APP_DIR, "settings.json")
            if os.path.exists(setting_path):
                with open(setting_path, "r") as settings_json:
                    raw_data = settings_json.read()

                    # Regulate the config into the format that kivy can accept
                    tmp = eval(raw_data)

                    default_val = {}

                    for index in range(len(tmp)):
                        if tmp[index]['type'] == 'title':
                            pass
                        elif 'default' in tmp[index]:
                            default_val[tmp[index]['key']
                                        ] = tmp[index]['default']

                    # Update the default value and setting menu
                    config.setdefaults(APP_NAME, default_val)
项目:RKSV    作者:ztp-at    | 项目源码 | 文件源码
def exportKeyStoreCb(self, path, filename):
        if not filename:
            return

        config = configparser.RawConfigParser()
        config.optionxform = str
        App.get_running_app().keyStore.writeStore(config)
        try:
            with open(os.path.join(path, filename), 'w') as f:
                config.write(f)

            App.get_running_app().curSearchPath = path
        except IOError as e:
            displayError(e)

        self.dismissPopup()
项目:RKSV    作者:ztp-at    | 项目源码 | 文件源码
def exportKeyStoreCb(self, path, filename):
        if not filename:
            return

        config = configparser.RawConfigParser()
        config.optionxform = str
        App.get_running_app().keyStore.writeStore(config)
        try:
            with open(os.path.join(path, filename), 'w') as f:
                config.write(f)

            App.get_running_app().curSearchPath = path
        except IOError as e:
            displayError(e)

        self.dismissPopup()
项目:displayminion    作者:cedarsuite    | 项目源码 | 文件源码
def __init__(self, client, **kwargs):
        self.client = client
        self.disp_size = [0, 0]
        self.child_size = Window.size

        self.canvas = RenderContext(use_parent_projection = True)
        with self.canvas:
            self.fbo = Fbo(size = Window.size, use_parent_projection = True)

        with self.fbo:
            ClearColor(0, 0, 0, 0)
            ClearBuffers()

        super(DisplaySource, self).__init__(**kwargs)

        self.texture = self.fbo.texture

        if self.client.config.get('outputs', 'shmsink') == 'yes':
            from .GStreamerOutput import GStreamerOutput
            self.shmsinkoutput = GStreamerOutput(self.texture)
        else:
            self.shmsinkoutput = False

        Window.bind(on_resize = self.resize)
项目:displayminion    作者:cedarsuite    | 项目源码 | 文件源码
def build(self):
        self.title = 'Cedar Display Client'

        if self.config.get('window', 'fullscreen') == 'yes':
            Window.fullscreen = 'auto'

        if kivy.utils.platform is 'windows':
            self.icon = 'logo/logo-128x128.png'
        else:
            self.icon = 'logo/logo-1024x1024.png'

        self.source = DisplaySource(self, pos_hint = {'x': 1, 'y': 1}, size_hint = [None, None])
        self.source.bind(on_touch_down = self.toggle_fullscreen)

        self.layout = FloatLayout()
        self.layout.add_widget(self.source)

        self.ui = UserInterface(self)

        return self.layout
项目:high-quality-chat    作者:b6938236    | 项目源码 | 文件源码
def __init__(self, **kwargs):
        super(HQC, self).__init__(**kwargs)
        self.config = hqc_config.get_instance(file="conn.conf")
        self.phone = HQCPhone(self.config)
        self.chat_client = None

        # Recorder object from audio module
        self.recorder = None
        # Recording directory
        self.storage_dir = self.config.get('AudioSettings', 'recording_location')
        self.session_name = datetime.now().strftime(constants.DATETIME_SESSION)
        self.audio_file_location = os.path.join(self.storage_dir, self.session_name)
        if not os.path.exists(self.audio_file_location):
            os.makedirs(self.audio_file_location)

        # color for gui text
        self.dark_blue = '2939b0'

    # Build should only handle setting up GUI-specific items
项目:high-quality-chat    作者:b6938236    | 项目源码 | 文件源码
def on_enter(self):

        # when we add children to the grid layout, its size doesn't change at
        # all. we need to ensure that the height will be the minimum required
        # to contain all the childs. (otherwise, we'll child outside the
        # bounding box of the childs)
        self.ids.audioSidebar.bind(minimum_height=self.ids.audioSidebar.setter('height'))
        progress_bar = ProgressBar( value=0, size_hint= (0.5, None))
        label = Label(text = 'Waiting', size_hint= (0.32, None))
        label2 = Label(text='N/A%', size_hint= (0.18, None))
        self.ids.audioSidebar.add_widget(label2)
        self.ids.audioSidebar.add_widget(progress_bar)
        self.ids.audioSidebar.add_widget(label)
        self.app.chat_client = HQCWSClient(self.app.config)
        self.app.chat_client.app = self.app
        self.app.chat_client.config = self.app.config
        # self.app.chat_client.send_sync(constants.SYN)

        # create a scroll view, with a size < size of the grid
        # root = ScrollView(size_hint=(None, None), size=(310, 460),
        #                   pos_hint={'center_x': .5, 'center_y': .5}, do_scroll_x=False)
        # root.add_widget(audioClipLayout)
        # self.ids.audioSidebar.add_widget(root)
项目:high-quality-chat    作者:b6938236    | 项目源码 | 文件源码
def save_settings(self, setting1):
        children = self.ids.devices.children[:]
        index = 0
        while children:
            child = children.pop()
            if index == 0:
                self.app.config.update_setting("AudioSettings", "mic", child.text)
            if index == 1:
                self.app.config.update_setting("AudioSettings", "speakers", child.text)
            if index == 2 and child.text == "Default":
                self.app.config.update_setting("LQRecordingSettings", "codec", "Default")
            if index == 2 and child.text != "Codec":
                codec = child.text
                newcodec = [codec[0:codec.find(',')]]
                newcodec += [codec[(codec.find(',')+ 1): codec.find("bps")]]
                newcodec += [codec[(codec.find("bps") + 3): codec.find("channels")]]
                self.app.config.update_setting("LQRecordingSettings", "codec", codec)
            index += 1
        if setting1 != '':
            self.app.config.update_setting("ChatSettings", "username", setting1)
        self.parent.current = 'main'
        print self.app.config.get_section("AudioSettings")
        print self.app.config.get_section("LQRecordingSettings")
项目:HeaTDV4A    作者:HeaTTheatR    | 项目源码 | 文件源码
def build_config(self, config):
        config.adddefaultsection("General")
        config.setdefault("General", "showonstartpage", u"??????? ?????")
        config.setdefault("General", "language", u"???????")
        config.setdefault("General", "showwarning", "1")
        config.setdefault("General", "resmessages", "1")
        config.setdefault("General", "authorization", "0")
        config.setdefault("General", "progresstextsize", "15")
        config.setdefault("General", "downloadkey", "0")
        config.setdefault("General", "downloadfolder",
                          {0: 'Downloads', 1: ''})
        config.setdefault("General", "user_reg",
                          {"login": "login", "password": "password"})

        config.adddefaultsection("Network")
        config.setdefault("Network", "authoconnect", "0")
        config.setdefault("Network", "checkattachtoforum", "1")
        config.setdefault("Network", "loadscr", "0")
        config.setdefault("Network", "authoupdate", "1")

        config.adddefaultsection("Mail")
        config.setdefault("Mail", "messagesread", "1")
        config.setdefault("Mail", "intervalscanmess", "10")

        config.adddefaultsection("Theme")
        config.setdefault("Theme", "theme", "blue_orange")
        config.setdefault("Theme", "edittheme", "0")
        config.setdefault("Theme", "createtheme", "0")
项目:HeaTDV4A    作者:HeaTTheatR    | 项目源码 | 文件源码
def on_config_change(self, config, section, key, value):
        """?????????? ??? ?????? ?????? ?? ?????? ???????? ?????????."""

        def select_callback(*args):
            file_manager.body.dismiss()
            self.downloadfolder[1] = file_manager.select_folder
            config.set("General", "downloadkey", "1")
            config.set("General", "downloadfolder", str(self.downloadfolder))
            config.write()

        # TODO: ???????? ???????? ??????? ?? ???? ? ????????? ???????????.
        if key == "downloadkey" and int(value):  # "????????? ????????"
            file_manager = \
                FileChooser(select_callback=select_callback, filter="folder",
                            title=core.string_lang_select_folder,
                            background_image=self.core.theme_decorator_window,
                            auto_dismiss=False,  size=(.85, .9),)
        elif key == "downloadkey" and not int(value):
            self.downloadfolder[1] = ""
            config.set("General", "downloadkey", "0")
            config.set("General", "downloadfolder", str(self.downloadfolder))
            config.write()
        elif key == "checkattachtoforum":  # "???????? ????? ??????"
            self.checkattachtoforum = int(value)
        elif key == "progresstextsize":  # "???????? ??????? ??????"
            self.window_text_size = int(value)
        elif key == "edittheme":  # "?????? ??????? ????????????? ????"
            self.edit_pallete_theme()
项目:HeaTDV4A    作者:HeaTTheatR    | 项目源码 | 文件源码
def set_password(self):
        """????????? ?????? ????????????."""

        def write_password(data):
            _user_reg = {"login": data[0].encode("hex"),
                         "password": data[1].encode("hex")}
            self.open_dialog = False

            # ???? ?????? ?? ???????.
            if _user_reg["login"] == "" or _user_reg["password"] == "":
                return
            else:
                self.config.set("General", "user_reg", _user_reg)
                self.config.write()

                self.user_reg["login"] = data[0]
                self.user_reg["password"] = data[1]

                registration_form.body.dismiss()
                self.Clock.schedule_once(lambda *args: self.connect(args), 0.2)

        self.open_dialog = True
        registration_form = \
            self.create_window(callback=write_password, size_x=self.CONST_SCREEN,
                               text=core.string_lang_input_password, password=True,
                               button_ok=core.string_lang_yes, param="logpass")
项目:mobileinsight-mobile    作者:mobile-insight    | 项目源码 | 文件源码
def _on_answer(self, instance, answer):
        if answer == "yes":
            config = ConfigParser()
            config.read('/sdcard/.mobileinsight.ini')
            config.set("mi_general","privacy",1)
            config.set("NetLogger","privacy",1)
            config.write()
            self.popup.dismiss()
        elif answer == "no":
            # global disagree_privacy
            # disagree_privacy = 1
            config = ConfigParser()
            config.read('/sdcard/.mobileinsight.ini')
            config.set("mi_general","privacy",1)
            config.set("NetLogger","privacy",0)
            config.write()
            self.popup.dismiss()
            # App.get_running_app().stop()
项目:mobileinsight-mobile    作者:mobile-insight    | 项目源码 | 文件源码
def build_settings(self, settings):

        with open("settings.json", "r") as settings_json:
            settings.add_json_panel(
                'General', self.config, data=settings_json.read())

        self.create_app_settings(self.config, settings)
项目:mobileinsight-mobile    作者:mobile-insight    | 项目源码 | 文件源码
def build_config(self, config):
        # Yuanjie: the ordering of the following options MUST be the same as
        # those in settings.json!!!
        config.setdefaults('mi_general', {
            'bcheck_update': 0,
            'log_level': 'info',
            'bstartup': 0,
            'bstartup_service': 0,
            'bgps': 1,
            'start_service': 'NetLogger',
            'privacy': 0,
        })
        self.create_app_default_config(config)
项目:mobileinsight-mobile    作者:mobile-insight    | 项目源码 | 文件源码
def check_update(self):
        """
        Check if new update is available
        """
        try:
            config = ConfigParser()
            config.read('/sdcard/.mobileinsight.ini')
            bcheck_update = config.get("mi_general", "bcheck_update")
            if bcheck_update == "1":
                import check_update
                check_update.check_update()
        except Exception as e:
            Logger.exception(traceback.format_exc())
项目:mobileinsight-mobile    作者:mobile-insight    | 项目源码 | 文件源码
def privacy_check(self):
        """
        Check if new update is available
        """
        try:
            config = ConfigParser()
            config.read('/sdcard/.mobileinsight.ini')
            privacy_agreed = int(config.get("mi_general", "privacy"))
            if privacy_agreed == 0:
                import privacy_app
                privacy_app.PrivacyApp().run()
                # if privacy_app.disagree_privacy:
                #     self.stop()
        except Exception as e:
            Logger.exception(traceback.format_exc())
项目:RKSV    作者:ztp-at    | 项目源码 | 文件源码
def importKeyStoreCb(self, path, filename):
        if not filename or len(filename) < 1:
            return

        try:
            full = os.path.join(path, filename[0])
            if full.endswith(".json"):
                with open(full) as f:
                    jsonKS = utils.readJsonStream(f)
                    App.get_running_app().keyStore = \
                            key_store.KeyStore.readStoreFromJson(jsonKS)
            else:
                config = configparser.RawConfigParser()
                config.optionxform = str
                with open(full) as f:
                    config.readfp(f)
                App.get_running_app().keyStore = \
                        key_store.KeyStore.readStore(config)

            App.get_running_app().curSearchPath = path
        except (IOError, UnicodeDecodeError, ValueError,
                configparser.Error) as e:
            displayError(e)
        except KeyError:
            displayError(_("Malformed crypto container"))

        self.dismissPopup()
        self.buildKSTree()
项目:RKSV    作者:ztp-at    | 项目源码 | 文件源码
def importKeyStoreCb(self, path, filename):
        if not filename or len(filename) < 1:
            return

        try:
            full = os.path.join(path, filename[0])
            if full.endswith(".json"):
                with open(full) as f:
                    jsonKS = utils.readJsonStream(f)
                    App.get_running_app().keyStore = \
                            key_store.KeyStore.readStoreFromJson(jsonKS)
            else:
                config = configparser.RawConfigParser()
                config.optionxform = str
                with open(full) as f:
                    config.readfp(f)
                App.get_running_app().keyStore = \
                        key_store.KeyStore.readStore(config)

            App.get_running_app().curSearchPath = path
        except (IOError, UnicodeDecodeError, ValueError,
                configparser.Error) as e:
            displayError(e)
        except KeyError:
            displayError(_("Malformed crypto container"))

        self.dismissPopup()
        self.buildKSTree()
项目:displayminion    作者:cedarsuite    | 项目源码 | 文件源码
def debug(self, *args):
        print(*args)
#        if self.config.get('debug'):
#            print(*args)
项目:displayminion    作者:cedarsuite    | 项目源码 | 文件源码
def update_minion_blocks(self, dt):
        # Note: Sections were originally named "blocks", so far I've been too lazy to rewrite all the cedarserver code to reflect the new name. -IHS
        start_length = len(self.sections)
        block_delta = len(self.minion['settings']['blocks']) - start_length

        if block_delta > 0:
            for n in range(block_delta):
                config = self.minion['settings']['blocks'][start_length + n]

                section = Section(
                    source = self.source,
                    block = config,
                    client = self
                )

                self.layout.add_widget(section)
                self.sections.append(section)

        elif block_delta < 0:
            for n in range(abs(block_delta)):
                section = self.sections.pop()
                self.layout.remove_widget(section)

        for index, section in enumerate(self.sections):
            config = self.minion['settings']['blocks'][index]
            if not section.block == config: # TODO add brightness etc.
                section.block = config
                section.recalc()
项目:displayminion    作者:cedarsuite    | 项目源码 | 文件源码
def build_config(self, config):
        config.setdefaults('connection', {
            'server': 'localhost:3000',
            '_id': '',
            'autoconnect': 'no',
        })

        config.setdefaults('window', {
            'fullscreen': 'no'
        })

        config.setdefaults('outputs', {
            'shmsink': 'no'
        })
项目:high-quality-chat    作者:b6938236    | 项目源码 | 文件源码
def build(self):
        # Kivy is stubborn and overrides self.config with a built-in ConfigParser
        self.config = hqc_config.get_instance(file="conn.conf")
        # Give the web socket a reference to the app
        gui = Builder.load_file("HQC.kv")
        self.root = gui
        # Link application to Screen Manager
        self.root.app = self
        return gui
项目:high-quality-chat    作者:b6938236    | 项目源码 | 文件源码
def update_role(self, role):
        self.config.update_setting("ChatSettings", "role", role)
项目:high-quality-chat    作者:b6938236    | 项目源码 | 文件源码
def play_clip(self, obj):
        """
        Plays the selected file.
        :param obj: ToggleButton object
        :return:
        """
        role = self.app.config.get('ChatSettings', 'role')
        if role == 'ARTIST':
            # TODO: This plays LQ files, not HQ files.  Call get_audio_from_filename and also give it a length
            # Get filename of the high quality clip associated with this play button
            filename = self.app.get_own_state()['audio_files'][obj.clip_no]
            _, tail = os.path.split(filename)
            # Get base name
            # root, _ = os.path.splitext(tail)

            # Get filename of the session high quality audio stream
            hq_audio = self.app.config.get_file_name(self.app.session_name, tail)

            # Play audio for 5 seconds
            print "playing " + str(hq_audio)

            audio.playback(hq_audio, 0)
        else:
            filename = obj.filename
            time = obj.length
            lq_audio = audio.get_audio_from_filename(filename,time,self.app.phone.recording_locations)
            print "Playing back {}".format(lq_audio)
            if lq_audio is not None:
                audio.playback(lq_audio['filename'], lq_audio['start_time'], lq_audio['end_time'])
            else:
                print "Error getting playback"
项目:high-quality-chat    作者:b6938236    | 项目源码 | 文件源码
def get_conn(self, producer_connection):
        def is_valid(value):
            if value != '' and len(value) != 0:
                return True
            else:
                return False

        connection_details = self.app.config.get_section('ConnectionDetails')

        self.parent.current = 'producer_session'

        file_name = self.app.config.get_file_name(self.app.session_name, datetime.now().strftime(constants.DATETIME_LQ))
        self.app.phone.make_call(connection_details['call_no'], connection_details['server'], file_name)
        self.app.lq_audio = self.app.phone.recording_start
        print "passing lq_audio to gui: " + self.app.lq_audio
项目:high-quality-chat    作者:b6938236    | 项目源码 | 文件源码
def generate_string(self, servername, username, password, callno):
        connection_string = self.app.config.make_conn_string(username, password, servername, callno)
        box = BoxLayout(orientation='vertical')
        connection_text = TextInput(text=connection_string, size_hint=(1,.75))
        dismissbtn = Button(text="Dismiss Pop-up", size_hint=(1,.25))
        box.add_widget(connection_text)
        box.add_widget(dismissbtn)
        popup = Popup(title = 'Connection String', content=box, auto_dismiss=False,
                      size=(400,400), size_hint=(None,None))
        dismissbtn.bind(on_press=popup.dismiss)
        popup.open()
项目:HeaTDV4A    作者:HeaTTheatR    | 项目源码 | 文件源码
def set_variable_from_settings(self):
        self.messagesread = self.config.getint(
            "Mail", "messagesread")
        self.intervalscanmess = self.config.getint(
            "Mail", "intervalscanmess")

        self.loadscr = self.config.getint(
            "Network", "loadscr")
        self.checkattachtoforum = self.config.getint(
            "Network", "checkattachtoforum")
        self.authoupdate = self.config.getint(
            "Network", "authoupdate")
        self.authoconnect = self.config.getint(
            "Network", "authoconnect")

        self.downloadkey = self.config.getint(
            "General", "downloadkey")
        self.downloadfolder = eval(self.config.get(
            "General", "downloadfolder"))
        self.window_text_size = self.config.getint(
            "General", "progresstextsize")
        self.language = core.select_locale[self.config.get(
            "General", "language")]
        self.showonstartpage = self.config.get(
            "General", "showonstartpage")
        self.authorization = self.config.getint(
            "General", "authorization")
        self.resmessages = self.config.getint(
            "General", "resmessages")
        _user_reg = eval(self.config.get(
            "General", "user_reg"))

        try:
            self.user_reg = {"login": _user_reg["login"].decode("hex"),
                             "password": _user_reg["password"].decode("hex")}
        except TypeError:
            self.user_reg = {"login": _user_reg["login"],
                             "password": _user_reg["password"]}
        except AttributeError:  # Python 3
            self.user_reg = {"login": _user_reg["login"],
                             "password": bytes.fromhex(
                                 _user_reg["password"]).decode('utf-8')}
项目:mobileinsight-mobile    作者:mobile-insight    | 项目源码 | 文件源码
def create_app_settings(self, config, settings):
        app_list = get_plugins_list()
        for app in app_list:
            APP_NAME = app
            APP_DIR = app_list[app][0]
            setting_path = os.path.join(APP_DIR, "settings.json")
            if os.path.exists(setting_path):
                with open(setting_path, "r") as settings_json:
                    raw_data = settings_json.read()

                    # Regulate the config into the format that kivy can accept
                    tmp = eval(raw_data)

                    result = "["
                    default_val = {}

                    for index in range(len(tmp)):
                        if tmp[index]['type'] == 'title':
                            result = result + '{"type": "title","title": ""},'
                        elif tmp[index]['type'] == 'options':
                            default_val[tmp[index]['key']
                                        ] = tmp[index]['default']
                            result = result + '{"type": "' + tmp[index]['type'] \
                                + '","title":"' + tmp[index]['title'] \
                                + '","desc":"' + tmp[index]['desc'] \
                                + '","section":"' + APP_NAME \
                                + '","key":"' + tmp[index]['key'] \
                                + '","options":' + json.dumps(tmp[index]['options']) \
                                + '},'
                        else:
                            default_val[tmp[index]['key']
                                        ] = tmp[index]['default']
                            result = result + '{"type": "' + tmp[index]['type'] \
                                + '","title":"' + tmp[index]['title'] \
                                + '","desc":"' + tmp[index]['desc'] \
                                + '","section":"' + APP_NAME \
                                + '","key":"' + tmp[index]['key'] \
                                + '"},'
                    result = result[0:-1] + "]"

                    # Update the default value and setting menu
                    settings.add_json_panel(APP_NAME, config, data=result)
项目:mobileinsight-mobile    作者:mobile-insight    | 项目源码 | 文件源码
def setup_logger(app_name):
    '''Setup the analyzer logger.

    NOTE: All analyzers share the same logger.

    :param level: the loggoing level. The default value is logging.INFO.
    '''
    level = logging.INFO

    config = ConfigParser()
    config.read('/sdcard/.mobileinsight.ini')
    if config.has_option('mi_general', 'log_level'):
        level_config = config.get('mi_general', 'log_level')
        if level_config == "info":
            level = logging.INFO
        elif level_config == "debug":
            level = logging.DEBUG
        elif level_config == "warning":
            level = logging.WARNING
        elif level_config == "error":
            level = logging.ERROR
        elif level_config == "critical":
            level = logging.CRITICAL

    l = logging.getLogger("mobileinsight_logger")
    if len(l.handlers) < 1:
        # formatter = MyFormatter(
        #     '%(asctime)s %(message)s',
        #     datefmt='%Y-%m-%d,%H:%M:%S.%f')
        formatter = MyFormatter('%(message)s')
        streamHandler = logging.StreamHandler()
        streamHandler.setFormatter(formatter)

        l.setLevel(level)
        l.addHandler(streamHandler)
        l.propagate = False

        log_file = os.path.join(
            mi2app_utils.get_mobileinsight_analysis_path(),
            app_name + "_log.txt")
        Logger.info('service: mi log file: ' + log_file)

        fileHandler = logging.FileHandler(log_file, mode='w')
        fileHandler.setFormatter(formatter)
        l.addHandler(fileHandler)
        l.disabled = False
项目:mobileinsight-mobile    作者:mobile-insight    | 项目源码 | 文件源码
def exec_legacy(arg):
    try:
        tmp = arg.split(":")
        if len(tmp) < 2:
            raise AssertionError("Error: incorrect service path: " + arg)
        app_name = tmp[0]
        app_path = tmp[1]

        # print "Service: app_name=",app_name," app_path=",app_path
        setup_logger(app_name)

        t = threading.Thread(target=alive_worker, args=(30.0,))
        t.start()

        app_dir = os.path.join(mi2app_utils.get_files_dir(), "app")
        # add this dir to module search path
        sys.path.append(os.path.join(app_dir, app_path))
        app_file = os.path.join(app_dir, app_path, "main.mi2app")
        Logger.info("Phone model: " + mi2app_utils.get_phone_model())
        Logger.info("Running app: " + app_file)
        # print arg,app_dir,os.path.join(app_dir, arg)

        namespace = {"service_context": mi2app_utils.get_service_context()}

        # Load configurations as global variables
        config = ConfigParser()
        config.read('/sdcard/.mobileinsight.ini')

        ii = arg.rfind('/')
        section_name = arg[ii + 1:]

        plugin_config = {}
        if section_name in config.sections():
            config_options = config.options(section_name)
            for item in config_options:
                plugin_config[item] = config.get(section_name, item)

        namespace["plugin_config"] = plugin_config

        gps_provider = GpsListener(on_gps)
        gps_provider.start()

        execfile(app_file, namespace)

        # print app_name, "stops normally"

    except Exception as e:
        # Print traceback logs to analysis
        tb_exc = traceback.format_exc()
        Logger.error(tb_exc)
        l = logging.getLogger("mobileinsight_logger")
        l.error(tb_exc)
        sys.exit(tb_exc)
项目:high-quality-chat    作者:b6938236    | 项目源码 | 文件源码
def record_button(self):
        """
        Records high quality audio files on the artist side.
        :return:
        """
        # Toggle recording
        rec_state = self.app.get_own_state()['recording']
        self.app.get_own_state()['recording'] = not rec_state

        if self.app.get_own_state()['recording']:
            # Update state
            self.app.chat_client.send_sync(constants.SYNC_START_RECORDING)
            # GUI update
            self.ids.record_button.source = SessionScreen.stop_theme
            # Start the progress effect
            progress_thread = threading.Thread(target=self.record_progress)
            progress_thread.start()

            filename = self.app.config.get_file_name(self.app.session_name,
                                                     datetime.now().strftime(constants.DATETIME_HQ))
            head, tail = os.path.split(filename)
            print "Creating: " + tail
            # Make sure folders exist
            if not os.path.exists(head):
                os.makedirs(head)
            # Makes a Recorder with the desired filename
            self.app.recorder = audio.Recorder(filename)
            # Add available audio file to state list
            self.app.add_audio_file(filename)
            # Starts writing to an audio file, including to disk
            self.app.recorder.start()  # Starts recording
            print "Recording..."
        else:
            # Update state
            self.app.chat_client.send_sync(constants.SYNC_STOP_RECORDING)
            # GUI update
            self.ids.record_button.source = SessionScreen.record_red
            # Closes recording threads
            self.app.recorder.stop()

            self.app.phone.stop_start_recording(datetime.now().strftime(constants.DATETIME_LQ))
            self.add_clip()  # adds to gui sidebar

            # Send a sync message for when a clip is available
            available_filename = self.app.get_latest_audio_file()
            _, tail = os.path.split(available_filename)
            self.app.chat_client.send_sync(constants.SYNC_FILE_AVAILABLE,
                                           filename=tail,
                                           length=audio.get_length(available_filename))
项目:high-quality-chat    作者:b6938236    | 项目源码 | 文件源码
def get_text(self, servername, username, password, callnumber):
        def is_valid(value):
            if value != '' and len(value) != 0:
                return True
            else:
                return False

        if is_valid(servername) and is_valid(username) and is_valid(password) and is_valid(callnumber):
            self.app.config.update_setting('ConnectionDetails', 'server', servername)
            self.app.config.update_setting('ConnectionDetails', 'user', username)
            self.app.config.update_setting('ConnectionDetails', 'password', password)
            self.app.config.update_setting('ConnectionDetails', 'call_no', callnumber)
            connection_details = {'server': servername, 'user': username, 'password': password, 'call_no': callnumber}

        else:
            connection_details = self.app.config.get_section('ConnectionDetails')

        # TODO: All of this code needs to be moved to another screen
        # The generation of connection strings should occur in a completely different screen
        # that is accessible from the main screen.  The producer should be able to enter in the 4 values
        # and it should output a connection string
        # conn_string = username + ';' + password + ";" + servername + ";" + callnumber
        # encoded = base64.b64encode(conn_string)
        # self.app.config.update_setting('ConnectionDetails', 'conn_string', encoded)
        # self.parent.current = 'session'
        #
        # # Make BoxLayout for multiple items
        # popup_box = BoxLayout(orientation='vertical')
        # # Make "Connection String" TextInput
        # popup_text = TextInput(text=encoded, size_hint=(1, .8))
        # popup_box.add_widget(popup_text)
        # # Make "Close" button for popup
        # close_button = Button(text='Close', size_hint=(.4, .2), pos_hint={'center_x': .5})
        # popup_box.add_widget(close_button)
        # popup = Popup(title='Connection String',
        #               content=popup_box,
        #               size_hint=(None, None), size=(400, 400),
        #               auto_dismiss=False)
        # close_button.bind(on_press=popup.dismiss)
        # # Open the popup
        # popup.open()

        self.parent.current = 'producer_session'

        file_name = self.app.config.get_file_name(self.app.session_name, datetime.now().strftime(constants.DATETIME_LQ))
        self.app.phone.make_call(connection_details['call_no'], connection_details['server'], file_name)
        self.app.lq_audio = self.app.phone.recording_start
        print "passing lq_audio to gui: " + self.app.lq_audio
项目:high-quality-chat    作者:b6938236    | 项目源码 | 文件源码
def get_text(self, conn_string):
        if conn_string is not None and len(conn_string) != 0:  # Use the provided connection string
            connection_details = self.app.config.parse_conn_string()

            if not connection_details['server'] \
                    and not connection_details['user'] \
                    and not connection_details['password'] \
                    and not connection_details['call_no']:
                self.app.config.update_setting('ConnectionDetails', 'server', connection_details['server'])
                self.app.config.update_setting('ConnectionDetails', 'user', connection_details['user'])
                self.app.config.update_setting('ConnectionDetails', 'password', connection_details['password'])
                self.app.config.update_setting('ConnectionDetails', 'call_no', connection_details['call_no'])

            else:
                print "Bad connection string"
                error_message = 'Sorry, that string is not valid'
                popup = Popup(title='Connection String Error',
                              content=Label(text=error_message),
                              size_hint=(None, None), size=(400, 400))
                popup.open()

        else:  # Use the saved config values
            connection_details = self.app.config.get_section('ConnectionDetails')

            def is_valid(value):
                if value != '' and value != 'None' and value is not None:
                    return True
                return False

            if not is_valid(connection_details['server']) \
                    or not is_valid(connection_details['user']) \
                    or not is_valid(connection_details['password']) \
                    or not is_valid(connection_details['call_no']):
                # If the stored values aren't valid, nogood
                print "No connection string and bad config values"
                error_message = 'Sorry, the configuration is not valid'
                popup = Popup(title='Connection String Error',
                              content=Label(text=error_message),
                              size_hint=(None, None), size=(400, 400))
                popup.open()

        if self.app.config.get('ChatSettings', 'role') == "ARTIST":
            self.parent.current = 'artist_session'
        else:
            self.parent.current = 'listener_session'

        filename = self.app.config.get_file_name(self.app.session_name, datetime.now().strftime(constants.DATETIME_LQ))
        self.app.phone.make_call(connection_details['call_no'], connection_details['server'], filename)