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)
python类app()的实例源码
def build(self):
global app
app = self
# background sound
# start the background music
# self.music = SoundLoader.load('sound/8bitattempt.ogg')
# self.music.bind(on_stop=self.sound_replay)
# self.music.play()
# sound
self.sound['swing'] = SoundLoader.load('sound/battle/swing.ogg')
self.sound['coin'] = SoundLoader.load('sound/inventory/chainmail1.ogg')
self.title = 'One RPG'
self.game = TurnBattle()
self.game.init()
# self.game.load_enermy()
# Clock.schedule_interval(self.game.update, 1.0 / 60.0)
return self.game
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)
def request_file(self, obj):
"""
Called upon when the user requests a file by clicking "Request" on a recording.
:param obj: ToggleButton object
:return: None
"""
role = self.app.config.get('ChatSettings', 'role')
if role == 'ARTIST':
# 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)
print "Requesting {}".format(tail)
# Send a sync message to request a file.
self.app.chat_client.send_sync(constants.SYNC_REQUEST_FILE,
filename=tail)
elif role == 'PRODUCER':
self.app.chat_client.send_sync(constants.SYNC_REQUEST_FILE, filename=obj.filename)
def on_enter(self):
if self.app.config.get('ChatSettings', 'role') == "PRODUCER":
files = self.app.get_own_state()['requested_files']
for file in files:
label = Label(text=file, size_hint=(1 / len(files), None))
self.ids.filelayout.add_widget(label)
elif self.app.config.get('ChatSettings', 'role') == "ARTIST":
files = self.app.get_own_state()['requested_files']
if files:
header_label = Label(text="Files being sent", size_hint=(1 / len(files), None), color=[0, 0, 0, 1])
self.ids.filelayout.add_widget(header_label)
for file in files:
full_path = self.app.config.get_file_name(self.app.session_name, file)
self.app.chat_client.send_file(full_path)
label = Label(text=file, size_hint=(1 / len(files), None), color=[0, 0, 0, 1])
self.ids.filelayout.add_widget(label)
else:
pass
def do_login(self, loginText, passwordText):
a = SnapDB()
val = a.checkLogin(nickname=loginText, password=passwordText)
userID = val[1]
if val[1] != None:
a = SnapDB()
a.getUserData(userID)
popup = Popup(title='Hola', content=Label(text='Hi '+localFiles.getLocalUserInfo()[2].split(" ")[0]+', happy snapchatting!'), size_hint=(None, None), size=(350, 200))
popup.open()
self.manager.transition = SlideTransition(direction="left")
self.manager.current = 'connected'
else:
popup = Popup(title='Error', content=Label(text='The password or username are incorrect. Try again.'), size_hint=(None, None), size=(350, 200))
popup.open()
app = App.get_running_app()
app.config.read(app.get_application_config())
app.config.write()
def switch_screen(self, style = 'slide', screen_to_switch = None, clear = False, prompt = None, *args):
'''
switch screen with given transition
if screen is not defined it will switch to the last remembered screen (screen variable: last_screen)
if clear is true it will overwrite screen variable: last_screen
'''
# #from kivy.uix.screenmanager import ScreenManager, FadeTransition#, SlideTransition, SwapTransition, WipeTransition, FallOutTransition, RiseInTransition
# #from kivy.garden.moretransitions import BlurTransition#,PixelTransition,RippleTransition,RVBTransition
# #app = App.get_running_app()
# #self.last_screen = app.root.current
# #SlideTransition, SwapTransition, WipeTransition, FallOutTransition, RiseInTransition, FadeTransition
# #PixelTransition,RippleTransition,BlurTransition,RVBTransition
# transitions = { #'rise' : RiseInTransition(),
# #'fall' : FallOutTransition(),
# 'slide' : SlideTransition(),
# #'blur' : BlurTransition(),
# #'fade' : FadeTransition() }
# #transition = SlideTransition(direction="left")
# self.transition = transitions[style] # setting transition style
self.transition.direction = 'down'
self.transition.duration = self.duration
cached_screen = self.current # caching current screen to write it later as last_screen
if screen_to_switch:
''' if there is target screen defined then switch to it '''
self.current = screen_to_switch
if prompt:
self.get_screen(self.current).set_prompt(prompt)
else:
''' else switch to last+screen '''
self.current = self.get_screen(self.current).last_screen
if self.get_screen(self.current).last_screen is None:
''' if current (newly switched) screen has no last_screen defined, then define it now from cached_screen '''
self.get_screen(self.current).last_screen = cached_screen
elif clear == True:
''' if clear is forced, then overwrite current last_screen with cached screen anyway '''
self.get_screen(self.current).last_screen = cached_screen
def on_start(self):
'''Configures app when it starts.'''
self.use_kivy_settings = False
from kivy.base import EventLoop, runTouchApp
EventLoop.window.bind(on_keyboard=self.hook_keyboard)
def connectionMade(self): # spojení navázáno
self.factory.app.on_connection(self.transport)
def dataReceived(self, data): # p?íjem dat
self.factory.app.print_message(data)
def __init__(self, app): # inicializace
self.app = app
def clientConnectionLost(self, conn, reason): # spojení ztraceno
if self.app.disconnect == False:
if self.app.version == '1.13':
self.app.version = '1.14'
elif self.app.version == '1.14':
self.app.version = '1.13'
self.app.connect_to_server()
else:
self.app.sm.current = "ConnectScreen"
Toast(text=self.app.L.STR_CONNECTION_FAILED, timeout=3).open()
print reason
def clientConnectionFailed(self, conn, reason): # spojení selhalo
self.app.sm.current = "ConnectScreen"
Toast(text=self.app.L.STR_CONNECTION_FAILED, timeout=3).open()
print reason
# Hlavní t?ída programu
def exit_open_popup(self, instance):
idx = self.app.available_screens.index('HomeScreen')
self.app.go_screen(idx)
return False
def onGoBack(self, app):
idx = app.available_screens.index('HomeScreen')
app.go_screen(idx)
# app.root.ids.sm.switch_to(app.home_screen)
# Filter
# Pick certain Type IDs to view
# To reset everything, press the Reset button
def get_plugins_list():
'''
Load plugin lists, including both built-in and 3rd-party plugins
'''
ret = {} # app_name->(path,with_UI)
APP_DIR = os.path.join(
str(current_activity.getFilesDir().getAbsolutePath()), "app/plugins")
l = os.listdir(APP_DIR)
for f in l:
if os.path.exists(os.path.join(APP_DIR, f, "main.mi2app")):
# ret.append(f)
ret[f] = (os.path.join(APP_DIR, f), False)
# Yuanjie: support alternative path for users to customize their own plugin
APP_DIR = main_utils.get_mobileinsight_plugin_path()
if os.path.exists(APP_DIR):
l = os.listdir(APP_DIR)
for f in l:
if os.path.exists(os.path.join(APP_DIR, f, "main_ui.mi2app")):
if f in ret:
tmp_name = f + " (plugin)"
else:
tmp_name = f
ret[tmp_name] = (os.path.join(APP_DIR, f), True)
elif os.path.exists(os.path.join(APP_DIR, f, "main.mi2app")):
if f in ret:
tmp_name = f + " (plugin)"
else:
tmp_name = f
ret[tmp_name] = (os.path.join(APP_DIR, f), False)
else: # create directory for user-customized apps
create_folder()
return ret
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
def join_listener(self):
self.app.update_role(constants.LISTENER)
self.parent.current = 'artistsessionjoining'
def join_artist(self):
self.app.update_role(constants.ARTIST)
self.parent.current = 'artistsessionjoining'
def add_file(self, file):
# Called when artist receives a sync request file
if file not in self.requested_files and self.app.chat_client:
print "Adding file" + file
self.app.chat_client.send_sync(constants.SYNC_REQUEST_FILE, file)
else:
print "Chat client not connected"
print self.requested_files
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"
def record_progress(self):
while self.app.get_own_state()['recording']:
time.sleep(0.05)
self.ids.progress_bar.value = (self.ids.progress_bar.value + 1) % 31 # datetime.now().second % 6.0
def toggle_mute(self):
# Toggles the linphone mic
self.app.phone.toggle_mic()
# Update the mic image
if self.app.phone.core.mic_enabled:
self.app.chat_client.send_sync(constants.SYNC_MIC_ON)
self.ids.mute_button.source = SessionScreen.un_muted_mic_image
else:
self.app.chat_client.send_sync(constants.SYNC_MIC_OFF)
self.ids.mute_button.source = SessionScreen.muted_mic_image
def on_leave(self, *args):
"""
Makes sure the SessionScreen is left properly
:param args:
:return:
"""
# If leaving the SessionScreen, make sure to stop recording
if self.app.get_own_state()['recording']:
self.record_button()
def on_enter(self):
self.app.update_role(constants.PRODUCER)
# TODO: Have GUI fill in pre-entered values
# Currently a blank field means use existing values, even if none exists
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
def leave_session(self):
self.app.chat_client.finish()
self.app.phone.hangup()
App.get_running_app().stop()
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()
def kill_clock(obj): #use on_release: app.kill_clock() to call
global clock
clock = 0
def add_clock(obj): #use on_release: app.add_clock() to call
global clock
clock = 1