class WeatherRoot(BoxLayout):
    carousel = ObjectProperty()
    current_weather = ObjectProperty()
    forecast = ObjectProperty()
    locations = ObjectProperty()
    add_location_form = ObjectProperty()

    def __init__(self, **kwargs):
        super(WeatherRoot, self).__init__(**kwargs)
        self.store = JsonStore("weather_store.json")
        if self.store.exists('locations'):
            current_location = self.store.get("locations")["current_location"]
            self.show_current_weather(current_location)

    def show_current_weather(self, location=None):
        self.clear_widgets()

        if self.current_weather is None:
            self.current_weather = CurrentWeather()
        if self.locations is None:
            self.locations = Factory.Locations()
            if (self.store.exists('locations')):
                locations = self.store.get("locations")['locations']
                self.locations.locations_list.adapter.data.extend(locations)

        if location is not None:
            self.current_weather.location = location
            if location not in self.locations.locations_list.adapter.data:
                self.locations.locations_list.adapter.data.append(location)
                self.locations.locations_list._trigger_reset_populate()
                self.store.put("locations",
                    locations=list(self.locations.locations_list.adapter.data),
                    current_location=location)

        self.current_weather.update_weather()
        self.add_widget(self.current_weather)

    def show_forecast(self, location=None):
        self.clear_widgets()

        if self.forecast is None:
            self.forecast = Factory.Forecast()

        if location is not None:
            self.forecast.location = location

        self.forecast.update_weather()
        self.add_widget(self.forecast)

    # BEGIN SHOW_MODAL_VIEW
    def show_add_location_form(self):
        self.add_location_form = AddLocationForm()
        self.add_location_form.open()
    # END SHOW_MODAL_VIEW

    def show_locations(self):
        self.clear_widgets()
        self.add_widget(self.locations)
Beispiel #2
0
class MbtMergeManager(object):
    """
    Keeps track mbtiles merging state (merged vs not merged)
    and handles merging.
    """
    def __init__(self):
        json_store_path = App.get_running_app().json_store_path
        self.store = JsonStore(json_store_path)

    def merge_not_merged(self):
        """
        Merges not merged files.
        """
        mbtmerge = MbtMerge()
        sources = self.not_merged()
        destination = App.get_running_app().main_mbtiles_path
        mbtmerge.merge(sources, destination)
        for source in sources:
            self.add_to_merged(source)

    def not_merged(self):
        """
        Returns the list of not merged files.
        """
        merged_list = self.merged()
        not_merged_list = App.get_running_app().mbtiles_paths
        for merged in merged_list:
          not_merged_list.remove(merged)
        return not_merged_list

    def merged(self):
        """
        Returns the list of merged files.
        """
        try:
            merged = self.store.get('merged_mbtiles')['list']
        except KeyError:
            merged = []
        return merged

    def add_to_merged(self, mbtiles_path):
        """
        Adds the mbtiles to the merged list.
        """
        merged = self.merged()
        merged.append(mbtiles_path)
        self.store.put('merged_mbtiles', list=merged)

    def remove_from_merged(self, mbtiles_path):
        """
        Removes the mbtiles from the merged list.
        """
        merged = self.merged()
        merged.remove(mbtiles_path)
        self.store.put('merged_mbtiles', list=merged)
 def storeformdata(self):
     store = JsonStore('forms.json')
     store.put('forms',
               walletname=self.input_name.text,
               sendtoaddress=self.input_address.text,
               amount=self.input_amount.text,
               mixin=self.input_mixin.text,
               paymentid=self.input_paymentid.text,
               mineraddress=self.minerurl_input.text,
               mineruser=self.mineruser_input.text,
               minerpw=self.minerpw_input.text,
               minerthreads=self.minerthreads_input.text)
Beispiel #4
0
class ScoreBar(BoxLayout):
    score = NumericProperty()
    hi_score = NumericProperty()
    game_id = StringProperty()
    players = NumericProperty()
    active_player = NumericProperty()

    def __init__(self,**kwargs):
        super(ScoreBar,self).__init__(**kwargs)
        self.store = JsonStore(os.path.join(get_user_path(),'scores.json'))
        self.bind(score = self.score_changed)
        self.set_game_id()

    def set_game_id(self, game_id = 'default', multiplayer = False):
        self.players = int(multiplayer) + 1
        self.active_player = 1
        self.game_id = game_id
        if self.players == 1:
            if self.store.exists(game_id):
                data = self.store.get(game_id)
                self.hi_score = data['high_score']
            else:
                self.hi_score = 0

    def score_changed(self, *args):
        if self.players == 2:
            return
        if self.game_id != 'default':
            date = uspac.fromutc(datetime.datetime.utcnow())
            game_id = 'd%i%i%i'%(date.year, date.month, date.day)
            if self.game_id != game_id:
                #daily challenge has finished, the game reverts to default type so we only update the default high score table
                self.set_game_id()
            else:
                #store the high score in the default table as well as in the daily table
                hi_score = 0
                if self.store.exists('default'):
                    data = self.store.get('default')
                    hi_score = data['high_score']
                if self.score > hi_score:
                    self.store.put('default',high_score=int(self.score))
        if self.score > self.hi_score:
            self.hi_score = self.score
            self.store.put(self.game_id,high_score=int(self.score))
        if platform == 'android' and self.players == 1:
            if self.score > 600:
                App.get_running_app().gs_achieve('achievement_score_of_600')
            if self.score > 800:
                App.get_running_app().gs_achieve('achievement_score_of_800')
            if self.score > 1000:
                App.get_running_app().gs_achieve('achievement_score_of_1000')
            if self.score > 1200:
                App.get_running_app().gs_achieve('achievement_score_of_1200')
Beispiel #5
0
class UrbanRoot(BoxLayout):
    urbansearch = ObjectProperty()
    urbandict = ObjectProperty()

    def __init__(self, **kwargs):
        super(UrbanRoot, self).__init__(**kwargs)
        self.store = JsonStore("dictionary.json")
        self.update_urbandict()

    def add_to_dictionary(self, word, definition, example):

        current = self.store.get('dictionary')['dictionary'] if self.store.exists('dictionary') else []
        d = {
            'word' : word.encode('utf-8'),
            'definition' : definition.encode('utf-8'),
            'example' : example.encode('utf-8')
        }

        if d not in current:
            current.append(d)
        self.store.put('dictionary', dictionary = list(current))
        self.update_urbandict()

        Popup(size_hint=(0.8,0.2),title='Success', content = Label(text = 'Word has been added into dictionary')).open()

    def update_urbandict(self):
        current = self.store.get('dictionary')['dictionary'] if self.store.exists('dictionary') else []

        self.urbandict.urbandictcontainer.clear_widgets()
        for d in current:
            item = Factory.UrbanItemDict()
            item.word = d['word'].encode('utf-8')
            item.definition = d['definition'].replace('\r','').replace('\t','').encode('utf-8')
            item.example = d['example'].replace('\r','').replace('\t','').encode('utf-8')

            self.urbandict.urbandictcontainer.add_widget(item)

    def remove_from_dict(self, word, definition, example):
        current = self.store.get('dictionary')['dictionary'] if self.store.exists('dictionary') else []

        d = {
            'word' : word.encode('utf-8'),
            'definition' : definition.encode('utf-8'),
            'example' : example.encode('utf-8')
        }

        if d in current:
            current.remove(d)

            self.store.put('dictionary', dictionary = list(current))
            print 'removed'
            self.update_urbandict()
Beispiel #6
0
class MainApp(App):
    #create the application screens
    def build(self):

        data_dir = getattr(self, 'user_data_dir') #get a writable path to save our score
        self.store = JsonStore(join(data_dir, 'score.json')) # create a JsonScore file in the available location

        if(not self.store.exists('score')): # if there is no file, we need to save the best score as 1
            self.store.put('score', best=1)

        if platform() == 'android': # if we are on Android, we can initialize the ADs service
            revmob.start_session('54c247f420e1fb71091ad44a')

        self.screens = {} # list of app screens
        self.screens['menu'] = MenuScreen(self) #self the MainApp instance, so others objects can change the screen
        self.screens['game'] = GameScreen(self)
        self.root = FloatLayout()

        self.open_screen('menu')

        self.sound = SoundLoader.load('res/background.mp3') # open the background music
        # kivy support music loop, but it was not working on Android. I coded in a different way to fix it
        # but if fixed, we can just set the loop to True and call the play(), so it'll auto repeat
        # self.sound.loop = True It # was not working on android, so I wrote the following code:
        self.sound.play() # play the sound
        Clock.schedule_interval(self.check_sound, 1) #every second force the music to be playing

        return self.root

    # play the sound
    def check_sound(self, dt = None):
        self.sound.play()

    # when the app is minimized on Android
    def on_pause(self):
        self.sound.stop() # the stop the sound
        Clock.unschedule(self.check_sound)
        if platform() == 'android': #if on android, we load an ADs and show it
            revmob.show_popup()
        return True

    # when the app is resumed
    def on_resume(self):
        self.sound.play() # we start the music again
        Clock.schedule_interval(self.check_sound, 1)

    # show a new screen.
    def open_screen(self, name):
        self.root.clear_widgets() #remove the current screen
        self.root.add_widget(self.screens[name]) # add a new one
        self.screens[name].run() # call the run method from the desired screen
    def get_public_key():
        if DataMode.communication in KivyLogger.base_mode:
            # get from communication
            pub_pem = KivyLogger.socket.recv(1024)
        else:
            private_key = RSA.generate(2048, e=65537)
            prv_pem = private_key.exportKey("PEM")
            store = JsonStore(KivyLogger.filename + '.enc')
            store.put('private_key', pem=prv_pem)

            pub_pem = private_key.publickey().exportKey("PEM")

        KivyLogger.public_key = RSA.importKey(pub_pem)
        pass
Beispiel #8
0
    def on_pre_leave(self, *args):
        if len(self.haberadi.text)<3 and len(self.takmaadi.text)<3:
            return
        js=JsonStore("UmutRss.json")
        fst=True
        url_str="{"
        for k,v in self.urls.items():
            if fst:
                url_str +=k+":"+v
                fst=False
            else:
                url_str += ","+k + ":" + v

        url_str +="}"
        js.put(self.haberadi.text,title=self.takmaadi.text,url=url_str)
class WeatherRoot(BoxLayout):
    current_weather = ObjectProperty()
    locations = ObjectProperty()

    # BEGIN LOAD_CURRENT
    def __init__(self, **kwargs):
        super(WeatherRoot, self).__init__(**kwargs)
        self.store = JsonStore("weather_store.json")
        if self.store.exists('locations'):
            current_location = self.store.get("locations")["current_location"]
            self.show_current_weather(current_location)
    # END LOAD_CURRENT

    def show_current_weather(self, location=None):
        self.clear_widgets()

        if self.current_weather is None:
            self.current_weather = CurrentWeather()
        if self.locations is None:
            self.locations = Factory.Locations()
            if (self.store.exists('locations')):
                locations = self.store.get("locations")['locations']
                self.locations.locations_list.adapter.data.extend(locations)

        # BEGIN PUT_CURRENT
        if location is not None:
            self.current_weather.location = location
            if location not in self.locations.locations_list.adapter.data:
                self.locations.locations_list.adapter.data.append(location)
                self.locations.locations_list._trigger_reset_populate()
                self.store.put("locations",
                    locations=list(self.locations.locations_list.adapter.data),
                    current_location=location)
        # END PUT_CURRENT

        self.current_weather.update_weather()
        self.add_widget(self.current_weather)

    def show_add_location_form(self):
        self.clear_widgets()
        self.add_widget(AddLocationForm())

    def show_locations(self):
        self.clear_widgets()
        self.add_widget(self.locations)
class WeatherRoot(BoxLayout):
    carousel = ObjectProperty()
    current_weather = ObjectProperty()
    forecast = ObjectProperty()
    locations = ObjectProperty()
    add_location_form = ObjectProperty()

    # BEGIN INIT
    def __init__(self, **kwargs):
        super(WeatherRoot, self).__init__(**kwargs)
        self.store = JsonStore("weather_store.json")
        if self.store.exists('locations'):
            locations = self.store.get('locations')
            self.locations.locations_list.adapter.data.extend(locations['locations'])
            current_location = locations["current_location"]
            self.show_current_weather(current_location)
        else:
            Clock.schedule_once(lambda dt: self.show_add_location_form())
    # END INIT

    # BEGIN SHOW_CURRENT_WEATHER
    def show_current_weather(self, location):
        if location not in self.locations.locations_list.adapter.data:
            self.locations.locations_list.adapter.data.append(location)
            self.locations.locations_list._trigger_reset_populate()
            self.store.put("locations",
                locations=list(self.locations.locations_list.adapter.data),
                current_location=location)

        self.current_weather.location = location
        self.forecast.location = location
        self.current_weather.update_weather()
        self.forecast.update_weather()

        self.carousel.load_slide(self.current_weather)
        if self.add_location_form is not None:
            self.add_location_form.dismiss()
        # END SHOW_CURRENT_WEATHER

    def show_add_location_form(self):
        self.add_location_form = AddLocationForm()
        self.add_location_form.open()
Beispiel #11
0
class ReGalData(object):
    servertypes = [
        import_module('regallery.servers.piwigo').ReGalServerPiwigo
    ]

    @staticmethod
    def get_servertypes():
        '''Returns a list with all valids server types'''
        return [cls.name for cls in ReGalData.servertypes]

    @staticmethod
    def get_sever(_type, url, user, pw):
        '''
        Get new instance of a server

        _type - type from get_servertypes()
        url - base url for server
        user - username
        pw - password
        '''
        for cls in ReGalData.servertypes:
            if cls.name == _type:
                return cls(url, user, pw)

        raise LookupError()

    def __init__(self):
        self._app = App.get_running_app()

        serverconfig = os.path.join(self._app.user_data_dir, 'servers.json')
        self._servers = JsonStore(serverconfig)

    def add_server(self, url, name, username, password):
        self._servers.put(name, url=url, username=username, password=password)

    def get_servers(self):
        servers = {}
        for name in self._servers:
            servers[name] = self._servers.get(name)
        return servers
Beispiel #12
0
class ClockApp(App):
    clearcolor = (0,0,0,1)
    
    def __init__(self,**kwargs):
        super(ClockApp,self).__init__(**kwargs)
        from os.path import join
        self.store = JsonStore(join(self.user_data_dir,"clockalarm.json"))
    
    def build(self):
        root = ClockWidget()
        
        root.init_alarms()
        
        self.root=root
        return self.root
    
    def on_pause(self):
        return True
    
    def on_resume(self):
        pass
    
    def get_alarm_from_store(self,id):
        if self.store.exists("alarms"):
            try:
                return self.store.get("alarms")["a{}".format(id)]
            except:
                return None
        
    def set_alarm_to_store(self,id,alarm):
        allAlarms = {}
        for i in range(1,5):
            if i == int(id):
                allAlarms["{}".format(i)]=alarm
            else:
                allAlarms["{}".format(i)]=app.get_alarm_from_store("{}".format(i))
                                                       
        self.store.put("alarms",a1=allAlarms["1"],a2=allAlarms["2"],a3=allAlarms["3"],a4=allAlarms["4"])
Beispiel #13
0
class Settings(object):

    MIN_TOASTING_TIME = 10
    MAX_TOASTING_TIME = 600

    FILENAME = 'sofatech_toaster_storage'
    SETTINGS_KEY = 'settings'

    def __init__(self):
        self._ip = '127.0.0.1'
        self._port = 50007
        self._store = JsonStore(Settings.FILENAME)

    @property
    def ip(self):
        return self._ip

    @ip.setter
    def ip(self, value):
        self._ip = value

    @property
    def port(self):
        return self._port

    @port.setter
    def port(self, value):
        self._port = value

    def load(self):
        if self._store.exists(Settings.SETTINGS_KEY):
            settings_dict = self._store.get(Settings.SETTINGS_KEY)
            self._ip = settings_dict['ip']
            self._port = settings_dict['port']

    def save(self):
        self._store.put(Settings.SETTINGS_KEY, ip=self._ip, port=self._port)
Beispiel #14
0
class addStory(object):
    '''
    This class is used for adding story to the game

    Syntax for the story is a key based dictionary, these keys are hexadacimal numbers
    that will be used to track progress. Starting point is 1, so if scenario 1 had 3
    possible options then there would be 11, 12, and 13. If 13 had 2 options then it would
    be 131, and 132. This will continue until there is a string of 16 characters

    basic syntax: {key
    '''

    def __init__(self):
        self.File = raw_input("Which story would you like to edit?\n\n").lower()
        self.data = JsonStore(self.File + '.json')
        self.start = 1 #default start code
        if self.data.count(): #If file has been started
            print '\nLooking for where you left off...\n'
            keys = self.data.keys()
            leftOff = int(keys[len(keys) - 1])
            print ('It seems like you left off at event number'
                    ' %d, so let\'s move on to number %d.'
                    % (leftOff, leftOff + 1)
                    )
            self.start = leftOff
        self.addToDBLoop(self.start)

    def addToDBLoop(self, number):
        event = raw_input('What is event number %d?\n' % number).lower()
        optionsStr = raw_input(('What are the available options for player?\n'
            'If none just type \'none\'.\n')).lower().split()
        c = 0
        options = {}
        for o in optionsStr:
            c += 1
            options[o] = str(number) + str(c)
        self.data.put(str(number), event = event, options = options)
class LoginScreen(Screen):
	store=''
	username=''
	def __init__(self,**kwargs):
		super(LoginScreen, self).__init__(**kwargs)
		Clock.schedule_once(self.update_layout,1/60)
	def update_layout(self,btn):           
		data_dir= App.get_running_app().user_data_dir+'/'
		self.store = JsonStore(join(data_dir, 'storage.json'))       
		try:    
			self.username=self.store.get('credentials')['username']
			exp_data.set_username(self.username)
			self.parent.current = 'ExperimentSelectScreen'
		except KeyError:
			box=BoxLayout(orientation= 'vertical',padding=(100,100,100,100))
			#l=Label(size_hint_y=0.25)
			#box.add_widget(l)
			box.add_widget(Label(text="Enter email",font_size= sp(30),size_hint_y=.5))
			self.t=TextInput(font_size= sp(30),size_hint_y=0.5)
			box.add_widget(self.t)
			box.add_widget(Button(text="Okay",on_press=self.change_screen,font_size=sp(25),size_hint_y=.25))
			#box.add_widget(l)
			self.add_widget(box)


		#     #AppScreen.store.put('credentials', username=username, password=password)
	def change_screen(self,btn):
		if len(self.t.text) == 0:         #deal with exception here of not selecting a single experiment
			error_popup=Popup(title='Error',content=Label(text="Email cannot be left blank")\
					,size_hint=(.75,.75),auto_dismiss=True)
			error_popup.open()
			Clock.schedule_interval(error_popup.dismiss, 3)
		else:
			self.store.put('credentials', username=self.t.text)
			self.username=self.store.get('credentials')['username']
			exp_data.set_username(self.username)
			self.parent.current = 'ExperimentSelectScreen'
Beispiel #16
0
    def __int__(self, **kwargs):
        super().__init__(**kwargs)
        store = JsonStore('hello.json')
        #put some values
        store.put('tito', name='Mathieu', org='kivy')
        store.put('tshirtman', name='Gabriel', age=27)
        store.put('tito', name='Mathieu', age=30)

        print('tito is', store.get('tito')['age'])
Beispiel #17
0
 def storefilepath(self, instance):
     pathstore = JsonStore("pathstore.json")
     pathstore.put("path", path=instance.selection)
     print instance.selection
     self.manager.current="category_screen"
class WeatherRoot(BoxLayout):
    current_weather = ObjectProperty()
    locations = ObjectProperty()
    forecast = ObjectProperty()

    def __init__(self, **kwargs):
        super(WeatherRoot, self).__init__(**kwargs)
        self.store = JsonStore("weather_store.json")

        if self.store.exists('locations'):
            current_location = self.store.get("locations")["current_location"]
            self.show_current_weather(current_location)

    def show_current_weather(self, location=None):
        self.clear_widgets()

        if self.current_weather is None:
            self.current_weather = CurrentWeather()
        if self.locations is None:
            self.locations = Factory.Locations()
            if self.store.exists('locations'):
                locations = self.store.get("locations")['locations']
                self.locations.locations_list.adapter.data.extend(locations)
        if location is not None:
            self.current_weather = CurrentWeather(location=location)

            adapter_data = self.locations.locations_list.adapter.data

            if location not in adapter_data:
                adapter_data.append(location)
                self.locations.locations_list._trigger_reset_populate()
                self.store.put("locations", locations=list(adapter_data),
                               current_location=location)

        self.current_weather.update_weather()
        self.add_widget(self.current_weather)

    def show_add_location_form(self):
        self.clear_widgets()
        self.add_widget(AddLocationForm())

    def show_locations(self):
        self.clear_widgets()

        self.add_widget(self.locations)

    def show_forecast(self, location=None):
        self.clear_widgets()

        if self.forecast is None:
            self.forecast = Factory.Forecast()

        if location is not None:
            self.forecast.location = location

        self.forecast.update_weather()
        self.add_widget(self.forecast)

    @staticmethod
    def format_location(location):
        return "{} ({})".format(*location)
Beispiel #19
0
 def on_add_filtered_list(self, instance, device_name):
     print("[StartingScreen] on_add_filtered_list")
     store = JsonStore("devices_list.json")
     if store.exists(device_name) is not True:
         print("Adding new device to the .json file...")
         store.put(device_name, name=device_name)
Beispiel #20
0
class DataBase:
    base_url = 'https://osptest-3ddc5.firebaseio.com/'
    url = ''
    secret = ''
    admin_password = ''

    def __init__(self, path, heroes_path, password_path, trucks_path, version):
        self.version = version
        self.heroes_path = heroes_path
        self.password_path = password_path
        self.trucks_path = trucks_path
        self.path = path
        self.store = JsonStore(path)
        with open("login_data/login", 'r') as file:
            self.user = file.read().split("\n")[0]
        with open("login_data/secret", 'r') as file:
            self.secret = file.read().split("\n")[0]
        self.url = self.base_url + self.user + self.secret

        self.firebase_patch_all()
        self.update_osp_data()

    def update_osp_data(self):
        try:
            string = str(requests.get(self.url).json()['heroes'])
            if string:
                with open(self.heroes_path, 'w') as file:
                    file.write(string)
        except Exception as connection_error:
            Logger.exception(str(connection_error))
        try:
            with open(self.heroes_path, 'r') as file:
                self.heroes = json.loads(str(file.read()).replace("'", '"'))
        except Exception as no_heroes_in_db:
            Logger.exception(str(no_heroes_in_db))
            self.heroes = ["brak strażaków w bazie"]
        try:
            string = str(requests.get(self.url).json()['trucks'])
            if string:
                with open(self.trucks_path, 'w') as file:
                    file.write(string)
        except Exception as connection_error:
            Logger.exception(str(connection_error))
        try:
            with open(self.trucks_path, 'r') as file:
                self.trucks = json.loads(str(file.read()).replace("'", '"'))
        except Exception as no_trucks_in_db:
            Logger.exception(str(no_trucks_in_db))
            self.trucks = ["brak zastepów w bazie"]
        try:
            string = str(requests.get(self.url).json()['passwd'])
            if string:
                with open(self.password_path, 'w') as file:
                    file.write(string)
        except Exception as no_password_in_db:
            Logger.exception(str(no_password_in_db))
        try:
            with open(self.password_path, 'r') as file:
                self.admin_password = file.readline()
        except Exception as no_password_file:
            Logger.exception(str(no_password_file))

    def update_reports_data(self):
        result = self.firebase_patch_all()
        if result == -1:
            Factory.connectionPopout().open()
        else:
            self.update_osp_data()
            Factory.updateOK().open()

    def put_report(self, uuid_num, id_number, dep_date, dep_time, spot_time,
                   location, type_of_action, section_com, action_com, driver,
                   perpetrator, victim, section, details, return_date,
                   end_time, home_time, meter_reading, km_location, completed,
                   truck_num):
        if uuid_num == "":
            uuid_num = str(uuid.uuid1())
        if section_com == "Dowódca sekcji":
            section_com = ""
        if action_com == "Dowódca akcji":
            action_com = ""
        if driver == "Kierowca":
            driver = ""
        if truck_num == "Zastęp":
            truck_num = ""
        self.store.put(uuid_num,
                       innerID=id_number,
                       depDate=dep_date,
                       depTime=dep_time,
                       spotTime=spot_time,
                       location=location,
                       type=type_of_action,
                       sectionCom=section_com,
                       actionCom=action_com,
                       driver=driver,
                       perpetrator=perpetrator,
                       victim=victim,
                       section=section,
                       details=details,
                       returnDate=return_date,
                       endTime=end_time,
                       homeTime=home_time,
                       stanLicznika=meter_reading,
                       KM=km_location,
                       modDate=self.get_date(),
                       ready=completed,
                       truck=truck_num)
        try:
            string = "{'" + uuid_num + "': " + str(
                self.store.get(uuid_num)) + "}"
            to_database = json.loads(string.replace("'", '"'))
            requests.patch(url=self.url, json=to_database)
            return 0
        except Exception as connection_error:
            Logger.exception(str(connection_error))
            return -1

    def delete_report(self, uuid_num):
        if self.store.exists(uuid_num):
            try:
                # requests.delete(url=self.url[:-5] + id_number + ".json")
                string = '{"deleted-' + uuid_num + '": "true"}'
                to_database = json.loads(string)
                requests.patch(url=self.url, json=to_database)
                self.store.delete(uuid_num)
            except Exception as connection_error:
                Factory.deletePopout().open()
                Logger.exception(str(connection_error))
        else:
            return -1

    def get_heroes(self):
        return self.heroes.get("all")

    def get_driver(self):
        return self.heroes.get("driver")

    def get_section_comm(self):
        return self.heroes.get("section")

    def get_action_comm(self):
        return self.heroes.get("action")

    def get_trucks(self):
        return self.trucks

    def firebase_patch_all(self):
        try:
            with open(self.path, 'r') as file:
                data = file.read()
                to_database = json.loads(data)
                requests.patch(url=self.url, json=to_database)
            to_database = json.loads('{"' + self.user + '": "' + self.version +
                                     '"}')
            requests.patch(url=self.base_url + "mobileVersion/" + self.secret,
                           json=to_database)
            return 0
        except Exception as connection_error:
            Logger.exception(str(connection_error))
            return -1

    def delete_all(self):
        string_all = ""
        try:
            for key in self.store.keys():
                # requests.delete(url=self.url[:-5] + key + ".json")
                string = '{"deleted-' + key + '": "true"}'
                string_all = string_all + string
                to_database = json.loads(string)
                requests.patch(url=self.url, json=to_database)
                self.store.clear()
        except Exception as connection_error:
            Factory.deletePopout().open()
            Logger.exception(str(connection_error))

    def get_report(self, id_number):
        for item in self.store.find(innerID=id_number):
            dane = self.store.get(item[0])
            id_number = dane['innerID']
            dep_date = dane['depDate']
            dep_time = dane['depTime']
            spot_time = dane['spotTime']
            location = dane['location']
            type_of_action = dane['type']
            section_com = dane['sectionCom']
            action_com = dane['actionCom']
            driver = dane['driver']
            perpetrator = dane['perpetrator']
            victim = dane['victim']
            section = dane['section']
            details = dane['details']
            return_date = dane['returnDate']
            end_time = dane['endTime']
            home_time = dane['homeTime']
            meter_reading = dane['stanLicznika']
            km_location = dane['KM']
            date = dane['modDate']
            completed = dane['ready']
            truck_num = dane['truck']
            return [
                item[0], id_number, dep_date, dep_time, spot_time, location,
                type_of_action, section_com, action_com, driver, perpetrator,
                victim, section, details, return_date, end_time, home_time,
                meter_reading, km_location, date, completed, truck_num
            ]
        else:
            return -1

    def get_all_friendly(self):
        result = []
        for item in self.store.keys():
            data = self.store.get(item)
            result.append(data["innerID"] + " " + data["location"])
        return result

    def find_inner_id(self, id_number):
        for _ in self.store.find(innerID=id_number):
            return True
        return False

    @staticmethod
    def get_date():
        return str(datetime.datetime.now()).split(".")[0]

    def get_user(self):
        return self.user

    def get_password(self):
        return self.admin_password

    def change_osp(self, user, password):
        with open("login_data/login", 'r') as file:
            old_user = file.read().split("\n")[0]
        if user != old_user:
            try:
                user_password = str(
                    requests.get(self.base_url + "passwd/" + user +
                                 self.secret).json())
                to_database = json.loads('{"' + user + '": "' + self.version +
                                         '"}')
                requests.patch(url=self.base_url + "mobileVersion/" +
                               self.secret,
                               json=to_database)
            except Exception as connection_error:
                Logger.exception(str(connection_error))
                return -2  # no connection
            if user_password == "UPDATE":
                return -3  # update neeeded
            if user_password == "None" or password != user_password:
                return -1  # wrong password

            self.url = self.base_url + user + self.secret
            try:
                string = str(requests.get(self.url).json()['heroes'])
                with open(self.heroes_path, 'w') as file:
                    file.write(string)
            except Exception as connection_error:
                Logger.exception(str(connection_error))
                with open(self.heroes_path, 'w') as file:
                    file.write("")
            try:
                with open(self.heroes_path, 'r') as file:
                    self.heroes = json.loads(
                        str(file.read()).replace("'", '"'))
            except Exception as no_heroes_in_db:
                Logger.exception(str(no_heroes_in_db))
                self.heroes = ["brak strażaków w bazie"]
            try:
                string = str(requests.get(self.url).json()['trucks'])
                with open(self.trucks_path, 'w') as file:
                    file.write(string)
            except Exception as connection_error:
                Logger.exception(str(connection_error))
            try:
                with open(self.trucks_path, 'r') as file:
                    self.trucks = json.loads(
                        str(file.read()).replace("'", '"'))
            except Exception as no_trucks_in_db:
                Logger.exception(str(no_trucks_in_db))
                self.trucks = ["brak zastepów w bazie"]
            try:
                string = str(requests.get(self.url).json()['passwd'])
                with open(self.password_path, 'w') as file:
                    file.write(string)
            except Exception as connection_error:
                Logger.exception(str(connection_error))
                self.url = self.base_url + self.user + self.secret
                return -2
            try:
                with open(self.password_path, 'r') as file:
                    self.admin_password = file.readline()
            except Exception as no_password:
                Logger.exception(str(no_password))
            self.store.clear()
            self.user = user
            with open("login_data/login", 'w') as file:
                file.write(user)
        return 0
Beispiel #21
0
class BrickanoidLogic():
    # all the bricks
    _bricks = []
    # all the balls
    _balls = []
    # the pad
    _pad = None
    # for performance counting
    _starting_time = None

    # # of lives
    _lives = 3
    # gam eover status
    _game_over = False
    # score
    _score = 0
    # hiscore
    _hiscore = 0
    #current level
    _level = 0
    # max level reached
    _hilevel = 1
    # process a fire event
    _process_fire = False
    # waiting for next level
    _level_clear = True
    #paused
    _pause = False
    #true if animation for new level must start
    _starting_new_level = True

    # game properties from gfx
    _unitary_width = 0
    _unitary_height = 0
    _screen_top = 0
    _screen_right = 0
    _screen_width = 0
    _game_screen = None
    _boundaries_line_bottom = None
    _boundaries_line_top = None
    _lives_lbl = None
    _score_lbl = None

    # level mgmt
    _level_loader = None

    def __init__(self, game_screen):
        self._game_screen = game_screen
        self._level_loader = brickanoid_levels.load_levels(self)

    def game_start(self):
        self._starting_time = perf_counter()

        self._unitary_width = self._game_screen.gfx_properties['unitary_width']
        self._unitary_height = self._game_screen.gfx_properties[
            'unitary_height']
        self._screen_top = self._game_screen.gfx_properties['screen_top']
        self._screen_right = self._game_screen.gfx_properties['screen_right']
        self._screen_width = self._game_screen.gfx_properties['screen_width']
        self._boundaries_line_bottom = self._game_screen.gfx_properties[
            'boundaries_line_bottom']
        self._boundaries_line_top = self._game_screen.gfx_properties[
            'boundaries_line_top']
        self._lives_lbl = self._game_screen.gfx_properties['lives_lbl']
        self._score_lbl = self._game_screen.gfx_properties['score_lbl']
        self._level_lbl = self._game_screen.gfx_properties['level_lbl']
        self._score_lbl_menu = self._game_screen.gfx_properties[
            'score_lbl_menu']
        self._hiscore_lbl_menu = self._game_screen.gfx_properties[
            'hiscore_lbl_menu']
        self._level_lbl_menu = self._game_screen.gfx_properties[
            'level_lbl_menu']
        self._level_spinner_menu = self._game_screen.gfx_properties[
            'level_spinner_menu']
        self._game_screen = self._game_screen.gfx_properties['game_screen']
        self._menu_screen = self._game_screen.menu_screen

        self._lives = 3
        self._game_over = False
        self._score = 0
        self._level = int(self._level_spinner_menu.text)
        self._process_fire = False
        self._level_clear = True
        self._pause = False
        self._bricks = []
        self._balls = []
        self._pad = None
        self._level_matrix = LevelMatrix(16, 16)
        self._has_touch_down = False
        self._starting_new_level = True
        self._moving_left = False
        self._moving_right = False

        self._store = JsonStore('brickanoid.json')
        try:
            store = self._store.get('hiscore')
            self._hiscore = int(store['value'])
            store = self._store.get('hilevel')
            self._hilevel = int(store['value'])
        except KeyError:
            self._store.put('hiscore', value=0)
            self._store.put('hilevel', value=1)
            #self._store.put('hilevel', 1)
            self._hiscore = 0
            self._hilevel = 1
        # his = list(self._store.find(name='hiscore'))
        # if len(his) > 0:
        #     self._hiscore = his[0][1]['value']
        self._hiscore_lbl_menu.text = str(self._hiscore)
        self._update_level_spinner()

    def _update_level_spinner(self):
        level_values = []
        for i in range(1, self._hilevel + 1):
            level_values.append(str(i))
        self._level_spinner_menu.values = level_values

        #self._check_end_level()

    # add a brick to level at column i (starting from left) and row j (starting from top)
    # uses next space avialable depending on previous bricks
    # if i = j = -1 simply find next space available
    def add_brick_to_screen(self, brick, i=-1, j=-1):
        if i == -1 or j == -1:
            for y, x in np.ndindex(
                (self._level_matrix.columns, self._level_matrix.rows)):
                if self._level_matrix.is_free(x, y, brick.bwidth,
                                              brick.bheight):
                    brick.pos = (self._screen_right +
                                 (x * self._unitary_width),
                                 self._screen_top - (y * self._unitary_height))
                    self._level_matrix.occupy(x, y, brick.bwidth,
                                              brick.bheight)
                    self._bricks.append(brick)
                    return True
        else:
            brick.pos = (self._screen_right + (i * self._unitary_width),
                         self._screen_top - (j * self._unitary_height))
            self._level_matrix.occupy(i, j, brick.bwidth, brick.bheight)
            self._bricks.append(brick)
            return True
        return False

    def _create_random_ball(self):
        ball = brickanoid_elements.BallAnoid()
        # put it at center of pad
        ball.pos = (self._pad.pos[0] + self._pad.widget.width / 2 - ball.radius, \
                    self._pad.pos[1] + self._pad.widget.height)
        ball.velocity = (0, 0)
        self._balls.append(ball)

    def _fire_balls(self):
        for ball in self._balls:
            if ball.is_idle():
                rr = randint(-15, +15)
                ball.velocity = Vector(
                    (0, self._unitary_height / 4)).rotate(rr)
                print("vector: (%d) %s" % (rr, repr(ball.velocity)))

    def _check_collision_balls_bricks(self):
        bricks_to_remove = []
        for ball in self._balls:
            if ball.is_idle():
                continue
            for brick in self._bricks:
                # horizontal collision from left
                if brick.widget.collide_point((ball.pos[0] + 2 * ball.radius),
                                              (ball.pos[1] + ball.radius)):
                    print(
                        "collisione LEFT in %d, %d - %d, %d" %
                        (ball.pos[0], ball.pos[1], brick.pos[0], brick.pos[1]))
                    vx, vy = ball.velocity
                    ball.velocity = -vx, vy
                    ball.pos[0] -= 2
                    self._game_screen.play_sound('brick_hit')
                    if brick.collided():
                        bricks_to_remove.append(brick)
                        self._score += brick.points

                # horizontal collision from right
                elif brick.widget.collide_point((ball.pos[0]),
                                                (ball.pos[1] + ball.radius)):
                    #if ball.widget.collide_widget(brick.widget):
                    print(
                        "collisione RIGHT in %d, %d - %d, %d" %
                        (ball.pos[0], ball.pos[1], brick.pos[0], brick.pos[1]))
                    vx, vy = ball.velocity
                    ball.velocity = -vx, vy
                    ball.pos[0] += 2
                    self._game_screen.play_sound('brick_hit')
                    if brick.collided():
                        bricks_to_remove.append(brick)
                        self._score += brick.points

                # vertical collision from bottom
                elif brick.widget.collide_point(
                    (ball.pos[0] + ball.radius),
                    (ball.pos[1] + 2 * ball.radius)):
                    print(
                        "collisione BOTTOM in %d, %d - %d, %d" %
                        (ball.pos[0], ball.pos[1], brick.pos[0], brick.pos[1]))
                    vx, vy = ball.velocity
                    ball.velocity = vx, -vy
                    ball.pos[1] -= 2
                    self._game_screen.play_sound('brick_hit')
                    if brick.collided():
                        bricks_to_remove.append(brick)
                        self._score += brick.points

                #vertical collision from top
                elif brick.widget.collide_point((ball.pos[0] + ball.radius),
                                                (ball.pos[1])):
                    print(
                        "collisione TOP in %d, %d - %d, %d" %
                        (ball.pos[0], ball.pos[1], brick.pos[0], brick.pos[1]))
                    vx, vy = ball.velocity
                    ball.velocity = vx, -vy
                    ball.pos[1] += 2
                    self._game_screen.play_sound('brick_hit')
                    if brick.collided():
                        bricks_to_remove.append(brick)
                        self._score += brick.points

        return bricks_to_remove

    def _check_collision_balls_border(self):
        deadballs = []

        for ball in self._balls:
            vx, vy = ball.velocity
            # right border
            if (ball.pos[0]) <= self._screen_right:
                vx *= -1
                ball.pos[0] += 1
                print("collisione X in %d, %d" % (ball.pos[0], ball.pos[1]))
            # right border
            elif (ball.pos[0] + 2 * ball.radius
                  ) >= self._screen_width - (2 * self._screen_right):
                vx *= -1
                ball.pos[0] -= 1
                print("collisione X in %d, %d" % (ball.pos[0], ball.pos[1]))
            # top bar
            elif ball.widget.collide_widget(self._boundaries_line_top):
                vy *= -1
                ball.pos[1] -= 1
                print("collisione Y in %d, %d" % (ball.pos[0], ball.pos[1]))
            # bottom
            elif ball.widget.collide_widget(self._boundaries_line_bottom):
                print("morte Y in %d, %d" % (ball.pos[0], ball.pos[1]))
                deadballs.append(ball)
            ball.velocity = vx, vy
        return deadballs

    def _check_collision_balls_pad(self):
        for ball in self._balls:
            if ball.is_idle():
                continue
            vx, vy = ball.velocity
            # if somehow the ball is going up, ignore this event
            if vy > 0.:
                continue
            # check if collision happens only from top
            # if self._pad.widget.collide_point(ball.pos[0] + ball.radius, ball.pos[1]) and \
            #     not self._pad.widget.collide_point(ball.pos[0], ball.pos[1] + ball.radius) and \
            #     not self._pad.widget.collide_point(ball.pos[0] + 2 * ball.radius, ball.pos[1] + ball.radius):
            if self._pad.widget.collide_widget(ball.widget) and \
                (self._pad.pos[1] + self._pad.widget.height) - ball.pos[1] < 10:
                print("preso pad in %d, %d" % (ball.pos[0], ball.pos[1]))
                vy *= -1
                offset = self._pad.pos[0] + (self._pad.widget.width /
                                             2) - (ball.pos[0] + ball.radius)
                ball.velocity = vx - offset / 4, vy
                self._game_screen.play_sound('pad_hit')

    def _check_end_life(self):
        if len(self._balls) == 0:
            print("MORTO!")
            self._game_screen.play_sound('game_over')
            if self._lives > 0:
                self._create_random_ball()
                self._lives -= 1
            return True

    def _check_end_level(self):
        # count only non-indestructible bricks
        actbricks = [brick for brick in self._bricks if brick.strength > 0]
        if len(actbricks) == 0 and not self._pause:
            # no more bricks
            print("VITTORIA!")

            self._level_matrix = LevelMatrix(16, 16)
            self._game_screen.clear_gfx()
            self._balls = []
            self._bricks = []
            self._pad = None
            self._level_clear = True
            self._level += 1
            self._starting_new_level = True
            return True
        return False

    def pause(self):
        self._pause = True

    def continue_level(self):
        self._pause = False
        if self._game_over:
            self.game_start()
        elif not self._level_clear:
            return
        self._game_screen.clear_gfx()
        if self._level == 0:
            self._level = 1
        self._level_loader.load_level(self._level)

        self._pad = brickanoid_elements.PadYellow_2()
        self._pad.pos = (self._screen_width // 2 -
                         self._pad._widget.width // 2,
                         self._screen_top - (24.5 * self._unitary_height))

        self._create_random_ball()
        self._level_clear = False

    def _check_fire(self):
        if self._process_fire:
            self._fire_balls()
            self._process_fire = False

    def touch_move(self, x, y):
        if not self._pad:
            return
        newx, newy = self._pad.pos
        newx = x - self._pad.widget.width / 2
        if newx < 0:
            newx = 0
        elif newx + self._pad.widget.width > self._screen_width:
            newx = self._screen_width - self._pad.widget.width
        self._pad.pos = (newx, newy)
        self._has_touch_down = False

        # see if any ball is stick to the pad and in case move it
        for ball in self._balls:
            if ball.is_idle():
                ball.pos = (newx + self._pad.widget.width / 2 - ball.radius, \
                    ball.pos[1])

    def touch_down(self, x, y):
        self._has_touch_down = True

    def touch_up(self, x, y):
        # touched and released.... a tap?
        if self._has_touch_down:
            self.fire()

    def move_left(self):
        self._moving_left = True
        self._moving_right = False

    def move_right(self):
        self._moving_left = False
        self._moving_right = True

    def stop_left(self):
        self._moving_left = False

    def stop_right(self):
        self._moving_right = False

    def fire(self):
        self._process_fire = True

    def game_update(self):
        '''
        1. muovo palline (secondo posizione e velocità) OK
        3. verifico collisione pad-pallina OK
        4. verifico collissione pallina-bricks OK
        5. verifica collisione pallina-nemici
        6. verifica collisione proiettili-bricks
        7. verifica collisione proiettili-nemici
        8. verifica collisione potenziamento-pad
        6. disegna sfondo
        7. disegna bricks OK
        8. disegna nemici
        9. disegna pad OK
        10. disegna proiettili
        11. verifica perdita vita OK
        11. verifica fine vite OK
        12. verifica vittoria livello OK
        '''

        #secs = int(perf_counter() - _starting_time)
        #game_screen.count_lbl.text = str(secs)
        #game_screen.score_lbl.text = str(secs*123)

        # game_screen.clear_gfx()
        if self._game_over:
            self._game_screen.to_menu()
            return

        self._score_lbl_menu.text = str(self._score)
        self._level_lbl_menu.text = str(self._level)

        # if self._game_screen.is_showing_banner():
        #     return

        if self._level == 0:
            self._check_end_level()

        if self._starting_new_level:
            self.continue_level()
            self._game_screen.show_banner("Level %d" % self._level)
            self._game_screen.play_sound('game_start')
            self._starting_new_level = False
            return

        elif self._check_end_level():
            #self._game_screen.to_menu()
            self._score += (self._level - 1) * 100
            #self.pause()
            self._starting_new_level = True
            if self._level > self._hilevel:
                self._hilevel = self._level
                self._store.put('hilevel', value=self._hilevel)
                self._update_level_spinner()
            self._game_screen.show_banner("Level %d clear" % (self._level - 1))
            return

        if self._pause:
            return

        self._check_fire()

        # move every ball
        for elem in self._balls:
            elem.move()

        # move te pad accoringly to its speed
        if self._pad:
            self._pad.move()
            if self._moving_left:
                self.touch_move(
                    self._pad.pos[0] - 5 + self._pad.widget.width / 2,
                    self._pad.pos[1])
            elif self._moving_right:
                self.touch_move(
                    self._pad.pos[0] + 5 + self._pad.widget.width / 2,
                    self._pad.pos[1])

        # check collision with bricks. Check if some brick has to be removed
        deadbricks = self._check_collision_balls_bricks()
        if len(deadbricks) > 0:
            for brick in deadbricks:
                self._game_screen.remove_gfx(brick.widget)
                self._bricks.remove(brick)

        # check if a ball reached bottom. If no balls remained it is Gave Over
        deadballs = self._check_collision_balls_border()
        if len(deadballs) > 0:
            for ball in deadballs:
                self._game_screen.remove_gfx(ball.widget)
                self._balls.remove(ball)
        if self._check_end_life():
            if self._lives == 0:
                self._game_screen.show_banner("Game Over")
                self._game_over = True

        self._check_collision_balls_pad()

        # show # of lives and score
        self._lives_lbl.text = str(self._lives)
        self._score_lbl.text = str(self._score)
        self._level_lbl.text = str(self._level)

        if self._score > self._hiscore:
            self._hiscore = self._score
            self._hiscore_lbl_menu.text = str(self._hiscore)
            self._store.put('hiscore', value=self._hiscore)

        # draw bricks, balls and the pad
        for elem in self._bricks:
            self._game_screen.draw_gfx(elem.widget)
        for elem in self._balls:
            self._game_screen.draw_gfx(elem.widget)

        if self._pad:
            self._game_screen.draw_gfx(self._pad.widget)
Beispiel #22
0
class DescargarApp(App):

    # Desactiva el cuadro de configuración genérico de Kivy
    use_kivy_settings = False

    # Para que no se cierre al cambiar de aplicación en Android
    def on_pause(self):
        return True

    def build(self):
        self.download_thread = None

        self.store = JsonStore("descargar-aragontv.json")

        if not self.store.exists("target_folder"):

            if self.get_platform_name()=="android":
                from jnius import autoclass
                Environment = autoclass('android.os.Environment')
                download_folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                self.store.put("target_folder",value=download_folder.getAbsolutePath() )
            else:
                self.store.put("target_folder",value=os.path.expanduser("~") )

        if not self.store.exists("source_url"):
            self.store.put("source_url",value="http://alacarta.aragontelevision.es/programas/chino-chano/por-la-sierra-de-armantes-28022016-1452")

        self.screen_manager = ScreenManager(transition=FadeTransition())
        
        self.paso1 = Paso1(name='Paso 1')
        self.paso1.ids.target_folder.text = self.store.get("target_folder")["value"]
        self.paso1.ids.page_url.text = self.store.get("source_url")["value"]

        self.paso2 = Paso2(name='Paso 2')
        self.paso3 = Paso3(name='Paso 3')
        self.screen_manager.add_widget(self.paso1)
        self.screen_manager.add_widget(self.paso2)
        self.screen_manager.add_widget(self.paso3)
        return self.screen_manager

    def dismiss_popup(self):
        self._popup.dismiss()

    def target_selected(self, path, filename):
        self._popup.dismiss()
        self.paso1.ids.target_folder.text = path
        self.store.put("target_folder",value=self.paso1.ids.target_folder.text)

    def target_selection(self):
        content = LoadDialog(load=self.target_selected, cancel=self.dismiss_popup)
        content.ids.filechooser.path = self.paso1.ids.target_folder.text
        self._popup = Popup(title="Elige destino", content=content, size_hint=(0.9, 0.9))
        self._popup.open()

    def message(self,title,body):

        content = MessageDialog()
        content.ids.message_body.text = body
        self._popup = Popup(title=title, content=content, size_hint=(0.8, 0.8))
        self._popup.open()

    def url_ready(self,page_url):
        print "url_ready"

        print self.paso1.ids.page_url.text

        if not self.paso1.ids.page_url.text.startswith("http://") and not self.paso1.ids.page_url.text.startswith("https://"):
            self.message("Hay un problema...","La URL que has introducido no es válida")
            return

        self.store.put("target_folder",value=self.paso1.ids.target_folder.text)
        self.store.put("source_url",value=self.paso1.ids.page_url.text)

        from core.item import Item
        item = Item(url=self.paso1.ids.page_url.text)

        from channels import aragontv
        item = aragontv.detalle_episodio(item)

        self.video_title = item.title
        self.media_url = item.media_url

        if self.media_url=="":
            self.message("Hay un problema...","No se puede encontrar un vídeo en esa URL")
            return

        self.screen_manager.current = self.screen_manager.next()

        self.paso2.ids.description.text = "[b]"+item.title+"[/b]\n\n"+item.plot

    def start_download(self):
        print "start_download"

        self.paso3.resultado = "Descargando "+self.media_url+"\n\n"

        self.screen_manager.current = self.screen_manager.next()

        # Start download in background
        from core import downloadtools
        clean_file_name = downloadtools.limpia_nombre_caracteres_especiales(self.video_title.decode("utf-8"))+".flv"
        #print "clean_file_name="+clean_file_name

        self.target_file = os.path.join( self.paso1.ids.target_folder.text , clean_file_name )
        #print "target_file="+self.target_file

        if self.get_platform_name()=="win":
            self.target_file = self.target_file.encode("utf-8")

        # get_platform_name es: win, linux, android, macosx, ios or unknown
        folder_platform = os.path.join( os.getcwd() , "rtmpdump" , self.get_platform_name() )
        print "folder_platform="+folder_platform
        if self.get_platform_name()=="win":
            rtmpdump = os.path.join(folder_platform,"rtmpdump.exe")
        elif self.get_platform_name()=="linux":
            rtmpdump = "rtmpdump"
        else:
            rtmpdump = os.path.join(folder_platform,"rtmpdump")

        # En Android hay que darle antes expresamente permisos de ejecución al binario de rtmpdump
        if self.get_platform_name()=="android":
            subprocess.Popen(["chmod","0755",rtmpdump], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

        exe = [rtmpdump]
        exe.append("-r")
        exe.extend(self.media_url.replace("app=","--app ").replace("playpath=","--playpath ").split(" "))
        #exe.append("--live")
        exe.append("-o")
        exe.append(self.target_file)

        self.paso3.ids.cargando.opacity=1

        self.download_thread = DownloadThread(exe,self.paso3)
        self.download_thread.start()

        Clock.schedule_interval(self.check_output_size, 0.5)

    def abort_download(self):
        print "abort_download"

        self.download_thread.abort()
        self.screen_manager.current = self.screen_manager.previous()

    def check_output_size(self,value):
        #print "check_output_size"

        if os.path.exists(self.target_file):
            statinfo = os.stat(self.target_file)
            self.paso3.tamanyo = human_size(statinfo.st_size)

    def on_stop(self):
        print "on_stop!"

        if self.download_thread is not None:
            self.download_thread.abort()

    def get_platform_name(self):
        from kivy import platform
        platform_name = str(platform)
        print "platform_name="+platform_name
        return platform_name
Beispiel #23
0
class PonumiPerformer(App):

    osc_ip_address = StringProperty(_default_osc_ip_address)
    osc_port = StringProperty(_default_osc_port)
    auto_generate_rhythm = BooleanProperty(_default_auto_generate_rhythm)

    osc_indicator = ObjectProperty(None)

    input_focus = ObjectProperty(None)

    poem_position = NumericProperty(0)
    rhythm_position = NumericProperty(0)

    def __init__(self, **kwargs):
        super(PonumiPerformer, self).__init__(**kwargs)
        data_dir = getattr(self, 'user_data_dir')
        self.config_store = JsonStore(join(data_dir, 'ponumiperformer.json'))
        self.rhythm = _default_rhythm

        self.initialise_osc()


    def initialise_osc(self):
        oscAPI.init()

        oscid = oscAPI.listen(ipAddr='127.0.0.1', port=osc_listen_port)
        oscAPI.bind(oscid, self.poem_position_changed, osc_poem_position)
        oscAPI.bind(oscid, self.rhythm_position_changed, osc_rhythm_position)
        self.osc_poll = Clock.schedule_interval(lambda *x: oscAPI.readQueue(oscid), 0.01)

        send_osc_message('/osc/respond_to', [osc_listen_port])
        send_osc_message(osc_poem_position, [0.0001], typehint=1.0)
        send_osc_message(osc_rhythm_position, [0.0001], typehint=1.0)


    def shutdown_osc(self):
        self.osc_poll.cancel()
        oscAPI.dontListen()


    def poem_position_changed(self, msg, *args):
        self.poem_position = int(msg[2])

    def rhythm_position_changed(self, msg, *args):
        self.rhythm_position = int(msg[2])


    def build(self):
        self.load_config()

        rootscreen = RootScreen()

        navbar = NavBar()
        self.osc_indicator = navbar.osc_indicator
        rootscreen.add_widget(navbar)
        self.screen_manager = PonumiPerformerScreenManager()
        rootscreen.add_widget(self.screen_manager)

        return rootscreen


    def save_config(self):

        self.config_store.put('config', 
            osc_ip_address=self.osc_ip_address,
            osc_port=self.osc_port)


    def load_config(self):

        if self.config_store.exists('config'):
            config = self.config_store.get('config')

            if 'osc_ip_address' in config: self.osc_ip_address = config['osc_ip_address']
            if 'osc_port' in config: self.osc_port = config['osc_port']


    def load_default_config(self):
        self.osc_ip_address = _default_osc_ip_address
        self.osc_port = _default_osc_port

    def on_stop(self):
        self.shutdown_osc()
Beispiel #24
0
class HomePage(Screen, Widget):
    def __init__(self, **kwargs):
        super(HomePage, self).__init__(**kwargs)
#References the json file called local.json
        self.store = JsonStore('local.json')
        print("whether previous exist = " + repr(self.store.exists('numEntries')))
#Determines if the server initiation is correct (should only be a one time thing)
        isSuccessful = True
        path = "/Users/ryan04px2021/Desktop/SAS/High_School/Junior_(11)/Afterschool_Activities/2020Summer/ActualSummer/CallForCode/CallForCode_COVID-19_Project/Kivy/Tutorials/11Test"
        client.init(path + "/sth.log", 10)
#Checks if there is a file. If there is not, initiate all 4 necessary parts
        if (not self.store.exists('numEntries')):
            print("enter")
            self.store.put("selfMac", value = "a2:4f:43:92:25:2e")
            tempSecret = client.initSelf(self.store.get("selfMac")["value"])
            if (tempSecret == 2):
                tempBut = Button(text = "Server Error, Please quit the app and try again (2)", font_size = 40)
                self.add_widget(tempBut)
                isSuccessful = False
            elif (tempSecret == 3):
                tempBut = Button(text = "User already initiated (3)", font_size = 40)
                self.add_widget(tempBut)
                isSuccessful = False
            elif (tempSecret == 4):
                tempBut = Button(text = "Invalid Mac Address, Please quit the app and try again (4)", font_size = 40)
                self.add_widget(tempBut)
                isSuccessful = False
            else:
                self.store.put("secretKey", value = tempSecret)
                self.store.put("numEntries", value = 0)
                self.store.put("macDict", value = dict())
                self.store.put("recentTen", value = list())
                self.store.put("prevNetwork", value = dict())
        if (isSuccessful):
            self.options = ObjectProperty(None)
#macClass variable is just used as a reference to be able to call the getMac class
            self.macClass = GetMacAdd()
            self.actualMac = self.macClass.getMac()
            self.status = "You are safe!"
    def coronaCatcherButtonClicked(self):
        print("coronaCatcherButton clicked")
        returnVal = client.queryMyMacAddr(self.store.get("selfMac")["value"], self.store.get("secretKey")["value"])
        if (returnVal == -1):
            self.status = "Checked by " + str(datetime.datetime.now()) + ", you have contacted someone with the virus. Please quarantine"
            print("You are infected")
        elif (returnVal == 0):
            self.status = "Checked by " + str(datetime.datetime.now()) + ", you are still safe!"
        elif (returnVal == 2):
            self.status = "Checked by " + str(datetime.datetime.now()) + ", Server Error, please quit the app and retry (2)"
        elif (returnVal == 3):
            self.status = "Checked by " + str(datetime.datetime.now()) + ", Incorrect secret key, you're kinda screwed (3)"
        elif (returnVal == 4):
            self.status = "Checked by " + str(datetime.datetime.now()) + ", Invalid mac address, you're kinda screwed (4)"
        else:
            self.status = "1 returned"



#This method is used when we click the button to check our current network mac
    def calculateMac(self):
        self.actualMac = self.macClass.getMac()
        self.coronaCatcherButtonClicked()
        return self.actualMac

    #This calculates the offset accordingly (topLeftH and topLeftW are both in terms of proportions)
    def findCoordinates(self, percentage, topLeftWidth, topLeftHeight):
        smallDim = min(Window.size)
        offSet = smallDim * percentage
        xCoor = topLeftWidth * Window.size[1] + offSet#Windows: (Height, Width)
        yCoor = topLeftHeight * Window.size[0] - self.options.size[0] - offSet
        print(xCoor / Window.size[1])
        print(yCoor / Window.size[0])
        return (xCoor / Window.size[1], yCoor / Window.size[0])

    pass
Beispiel #25
0
class MyRoot(ScreenManager):
    
    def __init__(self, debug, **kwargs):
        super(MyRoot, self).__init__(**kwargs)
        
        
        self.debug = True
        if self.debug:
            print('MyRoot debug enabled')

        
        self.data_store = JsonStore('./dat.json')
               
        self.feedDict = {}
        self.feedDict = self.get_rss_urls()
        self.entries = self.get_feed_entries()
        
        

        
        
    def build_rss_title_key(self, d):
        title = re.sub('[^0-9a-zA-Z]+', '_', d.feed.title).lower()
        return title
    
    
    def get_rss_urls(self):
        try:
            feeds = self.data_store.get('feeds')
            return feeds
        except:
            self.add_rss_feed("https://talkpython.fm/episodes/rss")
            self.get_rss_urls

    def get_feed_entries(self):
        try:
            entries = json.loads(self.data_store.get('feeds')['entries'])
            #print entries
            return entries
        except:
            return '[Fail] could not parse entries at get_feed_entries'
            
        
        
    def add_rss_feed(self, url):
        self.url = url
        self.post_dict_list = []
        
        try:
            d = feedparser.parse(self.url)
            
            self.status = d.status
            self.headers = d.headers
            self.title= d.feed.title
            self.rights= d.feed.rights
            self.subtitle= d.feed.subtitle

            for post in d.entries:
                self.post_dict_list.append({'published': str(datetimeparse(post.published)),
                                            'title': post.title,
                                            'link': post.link,
                                            'id': post.id,})
        except:
            if self.debug:
                message = '[Fail] add_rss_feed:', self.url
            else:
                message = '[Success] add_rss_feed', self.url
            return message
        
            
            
        try:
            feeds = self.data_store.get('feeds')[self.title]
            if self.debug:
                print '[success] found existing feeds', feeds
        except:
            if self.debug:
                print '[info] no feeds, adding default', self.title, self.url
                
            self.data_store.put('feeds', 
                                status= self.status, 
                                headers= self.headers, 
                                title=self.title, 
                                subtitle= self.subtitle, 
                                url=self.url, 
                                rights = self.rights,
                                entries=json.dumps(self.post_dict_list))
class Player(Widget):
    enmy_1 = ObjectProperty(None)  # enemy_1 refference
    enmy_2 = ObjectProperty(None)  # enemy_2 reference
    enmy_3 = ObjectProperty(None)  # enemy_3 refernce

    game_over = BooleanProperty(False)  #makes the gun not shootable

    countdown_going_on = BooleanProperty(True)
    #parent = ObjectProperty(None)

    put_limit_to_countdown_timer = BooleanProperty(False)

    sound = ObjectProperty(None, allownone=True)

    enemies = ListProperty([])

    image_1 = ObjectProperty(None)  # player ship body
    image_2 = ObjectProperty(None)  # ships bullet

    go = ObjectProperty()  # this will make ship move
    score = ObjectProperty(None)  # this will display score on screen
    popup = ObjectProperty(None)

    bullet_speed = ListProperty([0, 50])  # the speed of bullet
    velocity = ListProperty([5, 10])  # the movement speed of player

    time_count = NumericProperty()
    points = NumericProperty()  # point earned

    check_if_ship_collide = BooleanProperty(
        False)  # check to see if ourship collides with rocks
    check_if_ship_collide_timer = ObjectProperty(None)

    l_enabled = BooleanProperty(False)  # if left is pressed,bcomes True
    r_enabled = BooleanProperty(False)  # if right is pressed,becomes True
    moving = BooleanProperty(False)  # if the player is moving,bcomes True

    shooting = BooleanProperty(False)  # if it is shooting,becomes True

    # makes sure that this runs no matter what happens
    def __init__(self, **kwargs):
        super(Player, self).__init__(**kwargs)
        #register the keyboard
        self._keyboard = Window.request_keyboard(self._keyboard_closed, self,
                                                 'text')
        if self._keyboard.widget:
            pass
        self._keyboard.bind(on_key_down=self._on_keyboard_down,
                            on_key_up=self._on_key_up)
        # add the score display to the screen
        self.score = Score()
        self.add_widget(self.score)

        # points counter
        self.points = 0
        self.score.text = str(self.points)

        #get set go
        self.timer = Label(text='')
        self.timer.font_size = '80sp'
        self.timer.x = 100
        self.timer.y = 300
        self.add_widget(self.timer)

        self.put_limit_to_countdown_timer = True

        if self.put_limit_to_countdown_timer == True:
            #update time
            self.timer_schedule = Clock.schedule_interval(
                self.timer_update, 1.0)

    # this will update timer
    def timer_update(self, *args):
        self.time_count += 1
        self.timer.text = str(self.time_count)

        if self.time_count >= 4:
            self.timer.font_size = '100sp'
            self.timer.text = str('GO!')

        if self.time_count >= 5:
            self.countdown_going_on = False
            if self.sound == None:
                self.sound = SoundLoader.load('shoot.wav')
            #self.parent = Game()
            #print "done............ "
            Clock.unschedule(self.timer_schedule)
            self.remove_widget(self.timer)
            # add the enemy_1 to the screen
            self.enmy_1 = Enmy_1()
            self.add_widget(self.enmy_1)
            # start the enemy movement
            self.enmy_1.run = Clock.schedule_interval(self.enmy_1.update,
                                                      1.0 / 60.0)
            self.enemies.append(self.enmy_1)

            # add the enemy_2 to the screen
            self.enmy_2 = Enmy_2()
            self.add_widget(self.enmy_2)
            # start the enemy movement
            self.enmy_2.run = Clock.schedule_interval(self.enmy_2.update,
                                                      1.0 / 60.0)
            self.enemies.append(self.enmy_2)

            # add the enemy_2 to the screen
            self.enmy_3 = Enmy_3()
            self.add_widget(self.enmy_3)
            # start the enemy movement
            self.enmy_3.run = Clock.schedule_interval(self.enmy_3.update,
                                                      1.0 / 60.0)
            self.enemies.append(self.enmy_3)

            self.check_if_ship_collide_timer = Clock.schedule_interval(
                self.check_ship_collide, 1.0 / 60.0)
            #print 'countdown timer strted'

    # checks to see if ship collide with rocks
    def check_ship_collide(self, *args):
        for self.enmy in self.enemies:
            if self.image_1.collide_widget(self.enmy):
                Clock.unschedule(self.enmy_1.run)
                Clock.unschedule(self.enmy_2.run)
                Clock.unschedule(self.enmy_3.run)
                self.game_over = True  # makes it true so that we cannot shoot
                self.score.text = 'GAME OVER'
                self.Score_count()
                break  # break out of loop

    # this will save the score
    def Score_count(self):
        self.old_points = self.points

        self.score = JsonStore("score.json")
        if not self.score:
            self.score.put("score", score=self.old_points)
        else:
            if self.points >= self.score.get('score')['score']:
                self.old_points = self.points
                self.score.put("score", score=self.old_points)
                #self.menu.score_points.text = self.menu.score_points.text

    # check keyboard closed event
    def _keyboard_closed(self):
        #print "keyboard is closed"
        self._keyboard.unbind(on_key_down=self._on_keyboard_down)
        self._keyboard.unbind(on_key_up=self._on_key_up)
        self._keyboard = None

    # if key is pressed on keyboard then do the folowing...
    def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
        #if left is pressed and right is not presed
        if keycode[1] == "left" and self.r_enabled is False:
            #if the ship is not moving & it is not shooting...
            if self.moving == False and self.shooting == False:
                self.moving = True  # makes it true so that right cannot be pressed

                #move the player
                self.go = Clock.schedule_interval(self.go_left, 1.0 / 60.0)
            else:
                pass
            #print "you cant move left"

        if keycode[1] == "right" and self.l_enabled is False:
            if self.moving == False and self.shooting == False:
                self.moving = True
                self.go = Clock.schedule_interval(self.go_right, 1.0 / 60.0)
            else:
                pass
            #print "You cant move right"

        if keycode[1] == "spacebar" and self.countdown_going_on == False:
            if self.shooting == False and self.moving == False:
                if self.game_over == False:
                    self.moving = True
                    if self.sound == None:
                        self.sound = SoundLoader.load('shoot.wav')
                    if self.sound.status != 'stop':
                        self.sound.stop()
                    self.sound.play()
                    Clock.schedule_once(self.shoot, 1.0 / 60.0)

    #if the key is just pressed and released then do the following...
    def _on_key_up(self, keyboard, keycode, *args):
        if self.moving == True:  # if movng is True,
            Clock.unschedule(self.go)  # stop the player movement
            self.moving = False  # make it false
        if self.go:  # if any movement then stop it
            Clock.unschedule(self.go)

        if self.l_enabled is True:  # if left_pressed is true
            self.l_enabled = False  # then make it false
        if self.r_enabled is True:  # same as just above
            self.r_enabled = False

    # move the player to the right
    def go_right(self, dt):
        self.x += self.velocity[0]
        if self.x >= 255:
            Clock.unschedule(self.go)

    # move plater to the left
    def go_left(self, dt):
        self.x -= self.velocity[0]
        if self.x <= -35:
            Clock.unschedule(self.go)

    # make it shoot
    def shoot(self, dt):
        self.bullet_move = Clock.schedule_interval(self.move_bullet,
                                                   1.0 / 60.0)

    # make the bullet move
    def move_bullet(self, dt):
        self.image_2.y += self.bullet_speed[1]
        self.shooting = True
        self.check_collision()

    # check if it collides with enemy or boundary
    def check_collision(self):

        if self.enmy_1 in self.children:
            if self.image_2.collide_widget(
                    self.enmy_1):  # if it collides with enemy_1
                self.points += 1  # increment the score
                self.score.text = str(self.points)
                Clock.unschedule(self.bullet_move)  # stop the bullet movement
                self.remove_widget(self.image_2)  # remove the bullet
                Clock.unschedule(self.enmy_1.run)  # stop the enemy movement
                #self.children.remove(self.enmy_1)
                self.remove_widget(self.enmy_1)  # remove the enemy
                self.shooting = False  # make the shooting false
                #self.enmy_1.reload()
                #print "reloaded....."
                self.add_bullet()  # add the bullet again

        if self.enmy_2 in self.children:
            if self.image_2.collide_widget(
                    self.enmy_2):  # if it collides with enemy_1
                self.points += 1  # increment the score
                self.score.text = str(self.points)
                Clock.unschedule(self.bullet_move)  # stop the bullet movement
                self.remove_widget(self.image_2)  # remove the bullet
                Clock.unschedule(self.enmy_2.run)  # stop the enemy movement
                #self.children.remove(self.enmy_1)
                self.remove_widget(self.enmy_2)  # remove the enemy
                self.shooting = False  # make the shooting false
                #self.enmy_1.reload()
                #print "reloaded....."

                self.add_bullet()  # add the bullet again

        if self.enmy_3 in self.children:
            if self.image_2.collide_widget(
                    self.enmy_3):  # if it collides with enemy_1
                self.points += 1  # increment the score
                self.score.text = str(self.points)
                Clock.unschedule(self.bullet_move)  # stop the bullet movement
                self.remove_widget(self.image_2)  # remove the bullet
                Clock.unschedule(self.enmy_3.run)  # stop the enemy movement
                #self.children.remove(self.enmy_1)
                self.remove_widget(self.enmy_3)  # remove the enemy
                self.shooting = False  # make the shooting false
                #self.enmy_1.reload()
                #print "reloaded....."

                self.add_bullet()  # add the bullet again

        if self.image_2.y >= 600:  # if bullet goes out of boundary
            #print "beyond 600"
            Clock.unschedule(self.bullet_move)  # stop the movement
            self.remove_widget(self.image_2)  # remove the bullet
            self.shooting = False  # make shooting false
            self.add_bullet()  # add bullet

    # function to add the bullet
    def add_bullet(self):
        self.add_widget(self.image_2)  # add the bullet
        self.x += 0.1  # update it
        if not self.enmy_1 in self.children:  # if there is no enemy_1
            self.add_widget(self.enmy_1)  # add it
            self.enmy_1.x = randint(50, 250)
            self.enmy_1.y = randint(550, 600)
            self.enmy_1.run = Clock.schedule_interval(self.enmy_1.update,
                                                      1.0 / 60.0)

        if not self.enmy_2 in self.children:  # if there is no enemy_1
            self.add_widget(self.enmy_2)  # add it
            self.enmy_2.x = randint(50, 250)
            self.enmy_2.y = randint(550, 600)
            self.enmy_2.run = Clock.schedule_interval(self.enmy_2.update,
                                                      1.0 / 60.0)

        if not self.enmy_3 in self.children:  # if there is no enemy_1
            self.add_widget(self.enmy_3)  # add it
            self.enmy_3.x = randint(50, 250)
            self.enmy_3.y = randint(550, 600)
            self.enmy_3.run = Clock.schedule_interval(self.enmy_3.update,
                                                      1.0 / 60.0)

    def stop(self):
        Background().stop()
Beispiel #27
0
from kivy.storage.jsonstore import JsonStore

store = JsonStore('hello.json')

# put some values
store.put('tito', name='Mathieu', org='kivy')
store.put('tshirtman', name='Gabriel', age=27)

# using the same index key erases all previously added key-value pairs
store.put('tito', name='Mathieu', age=30)

# get a value using a index key and key
print('tito is', store.get('tito')['age'])

# or guess the key/entry for a part of the key
for item in store.find(name='Gabriel'):
    print('tshirtmans index key is', item[0])
    print('his key value pairs are', str(item[1]))
Beispiel #28
0
class MainApp(App):
    """
    _DEF_EX = exchange (for now hard coded to 'Binance')
    _DEF_SYM = symbol (for now default is 'btcusdt')
    _DARK_MODE_RGB = RGB for dark mode
    _LIGHT_MODE_RGB = RGB for light mode
    _DEF_MODE = default view mode
    _DEFAULT_NEWS_MODE = default status for displaying news
    _DEF_CUM_PNL = default cumulative pnl
    _DEFAULT_FEES = default user fees
    _PNL_PERC = decimal percision for pnl display
    _DEF_DATAJSON_NAME = json filename for user settings

    current_position - current position being held (1 for long, -1 for short, 0 for none)
    entry_price - entry price for current position
    last_price
    zero_pnl - macro string used to reset PnL
    cumulative_pnl - PnL of all positions
    current_pnl - PnL of current position being held

    position_mapping - convert from int to str representation of position type
    display_mode_mapping - convert from integer to str representation of display mode

    _GIT_URL -  the developer's GITHUB url
    about_info - the text to be displayed in the about window
    """
    _DARK_MODE_RGB = (0, 0, 0)
    _TEXT_COLOR_DARKMODE = get_color_from_hex("#ffffff")
    _LIGHT_MODE_RGB = (227 / 255, 214 / 255, 177 / 255)
    _TEXT_COLOR_LIGHTMODE = get_color_from_hex("#000000")
    _DEF_EX = "Binance"
    _DEF_SYM = "BTCUSDT"
    _DEF_DISP_MODE = 0
    _DEFAULT_NEWS_MODE = True
    _DEF_CUM_PNL = 0.0
    _DEFAULT_FEES = 0.0
    _PNL_PERC = 2
    _DEF_DATAJSON_NAME = "user_data"

    _GREEN_HEX = "#00b82b"
    _RED_HEX = "#b80000"

    price_fetcher = Fetcher(_DEF_EX)
    current_position = int()
    entry_price = float()
    last_price = float()
    zero_pnl = "0.00%"
    current_pnl = 0.0

    position_mapping = {1: 'Long', 0: 'Neutral', -1: 'Short'}

    display_mode_mapping = {0: 'Dark Mode', 1: 'Light Mode'}

    _GIT_URL = "https://github.com/adanikel"
    about_info = f'This is an open source game designed to ' \
                 f'simulate real-life trading by fetching a live price feed ' \
                 f'from top crypto exchanges (currently only Binance is supported).' \
                 f'\n\n\n' \
                 f'Made by [ref={_GIT_URL}][color=0000ff]adanikel[/color][/ref]'

    def build(self):
        """
        main_layout  (used as class attr)
            symbol_label - see current symbol
            price_label - live price feed
            pnl_label - live PnL of current position
            entry_price_status_layout
                pos_str_label - string representation of current position
                entry_price_label - entry price of current position
            news_label - news flash
            options_layout - to add padding to the button
                button_refresh - a refresh button for the cumulative PnL
                button_settings - a button to open settings menu
                    popup_settings - a popup window for settings
                        symbols_list -  dropdown list for symbols
                        button_display_mode - toggle view mode (dark or light)
                        button_news - turn on / off newsflash
                        button_fees - popup page to fees
                            fees_label - display fees
                            fees_up_button - increment fees
                            fees_down_button - decrement fees
                        button_about - display about
                cum_pnl_label
            position_buttons_layout
                button_buy
                button_sell
        """

        self.store = JsonStore(f'{self._DEF_DATAJSON_NAME}.json')
        self.load_user_data()

        self.main_layout = BoxLayout(orientation="vertical")

        self.main_layout.add_widget(Pulser.bg_pulser)
        with self.main_layout.canvas:
            Rectangle(source="icons/lightning.png",
                      size=(1450, 1450),
                      pos=(0, 550))
        self.symbol_label = Label(text='',
                                  bold=True,
                                  size_hint=(.5, .5),
                                  font_size=100,
                                  pos_hint={
                                      'center_x': .5,
                                      'center_y': 1
                                  },
                                  color=(237 / 255, 142 / 255, 43 / 255, 0.4))
        self.main_layout.add_widget(self.symbol_label)  # add price label

        self.price_label = Label(text='0.0',
                                 bold=True,
                                 size_hint=(.8, .8),
                                 font_size=250,
                                 pos_hint={
                                     'center_x': .5,
                                     'center_y': .9
                                 })
        self.main_layout.add_widget(self.price_label)  # add price label

        self.pnl_label = Label(text=self.zero_pnl,
                               bold=True,
                               size_hint=(.5, .5),
                               font_size=100,
                               pos_hint={
                                   'center_x': .5,
                                   'center_y': .9
                               })
        self.main_layout.add_widget(self.pnl_label)  # add price label

        entry_price_status_layout = BoxLayout(orientation='horizontal')
        self.pos_str_label = Label(text='',
                                   bold=True,
                                   size_hint=(.5, .5),
                                   font_size=60,
                                   pos_hint={
                                       'center_x': .5,
                                       'center_y': .9
                                   })
        entry_price_status_layout.add_widget(
            self.pos_str_label)  # add price label
        self.entry_price_label = Label(text='0.00',
                                       italic=True,
                                       size_hint=(.5, .5),
                                       font_size=60,
                                       pos_hint={
                                           'center_x': .5,
                                           'center_y': .9
                                       })
        entry_price_status_layout.add_widget(
            self.entry_price_label)  # add price label
        self.main_layout.add_widget(entry_price_status_layout)

        self.news_label = Label(text='',
                                size_hint=(.5, .5),
                                font_size=60,
                                pos=(0, 0))
        self.main_layout.add_widget(self.news_label)

        options_layout = BoxLayout(
            orientation="horizontal",
            # padding=[200, 100, 100, 100],
            pos_hint={
                'center_x': 0.6,
                'center_y': 0.5
            },
            spacing=100)
        self.button_settings = Button(text='',
                                      size_hint=(None, None),
                                      size=(170, 170),
                                      pos_hint={
                                          'center_x': .5,
                                          'center_y': .5
                                      })
        self.button_settings.bind(on_press=self.on_press_settings)
        options_layout.add_widget(self.button_settings)
        self.button_refresh = Button(text='',
                                     size_hint=(None, None),
                                     size=(170, 170),
                                     pos_hint={
                                         'center_x': .5,
                                         'center_y': .5
                                     })
        self.button_refresh.bind(on_press=self.on_press_refresh)
        options_layout.add_widget(self.button_refresh)
        self.cum_pnl_label = Label(text='',
                                   bold=True,
                                   size_hint=(.5, .5),
                                   font_size=140,
                                   pos_hint={
                                       'center_x': .5,
                                       'center_y': .5
                                   })
        options_layout.add_widget(self.cum_pnl_label)

        self.main_layout.add_widget(options_layout)

        position_buttons_layout = BoxLayout(orientation="horizontal",
                                            size_hint=(1, 0.5))
        button_buy = Button(text='Buy',
                            bold=True,
                            size_hint=(.8, .8),
                            pos_hint={
                                'center_x': .5,
                                'center_y': .8
                            },
                            background_color=get_color_from_hex("#3de03a"))
        button_buy.bind(on_press=self.on_press_buy)
        position_buttons_layout.add_widget(button_buy)

        button_sell = Button(text='Sell',
                             bold=True,
                             size_hint=(.8, .8),
                             pos_hint={
                                 'center_x': .5,
                                 'center_y': .8
                             },
                             background_color=get_color_from_hex("#eb3838"))
        button_sell.bind(on_press=self.on_press_sell)
        position_buttons_layout.add_widget(button_sell)

        self.main_layout.add_widget(position_buttons_layout)

        self.start_ticker(self.current_symbol)

        self.popup_settings = Popup(
            title='Settings',
            size_hint=(0.5, 0.5),
            background='icons/secondary_background.png',
            background_color=[1, 1, 1, .5],
            on_dismiss=self.save_user_data)
        self.settings_buttons = BoxLayout(orientation="vertical",
                                          padding=[0, 0, 0,
                                                   700])  # in pc, use 100

        self.symbols_dropdown = DropDown(max_height=650)
        for symbol in self.price_fetcher.get_all_symbols():
            symbol_button = Button(text=symbol.upper(),
                                   size_hint_y=None,
                                   height=125)
            symbol_button.bind(on_release=lambda symbol_button: self.
                               symbols_dropdown.select(symbol_button.text))
            self.symbols_dropdown.add_widget(symbol_button)

        self.main_symbol_button = Button(text=self.current_symbol.upper(),
                                         pos_hint={
                                             'center_x': .5,
                                             'center_y': .8
                                         })
        self.main_symbol_button.bind(on_release=self.symbols_dropdown.open)
        self.symbols_dropdown.bind(on_select=self.change_ticker)

        self.settings_buttons.add_widget(self.main_symbol_button)

        self.button_display_mode = Button(text='',
                                          pos_hint={
                                              'center_x': .5,
                                              'center_y': .5
                                          })
        self.button_display_mode.bind(on_press=self.set_display_mode)
        self.settings_buttons.add_widget(self.button_display_mode)

        self.about_label = Label(text=self.about_info,
                                 markup=True,
                                 on_ref_press=self.on_ref_press,
                                 pos_hint={
                                     'center_x': .5,
                                     'center_y': 1
                                 })
        self.about_label.bind(size=lambda s, w: s.setter('text_size')
                              (s, w))  # to limit text into popup

        self.about_window = Popup(title='About',
                                  size_hint=(0.5, 0.5),
                                  background_color=[1, 1, 1, .5],
                                  content=self.about_label)

        self.news_fetcher = NewsFetcher()
        self.button_news = Button(text=self.generate_news_button_text(),
                                  pos_hint={
                                      'center_x': .5,
                                      'center_y': .5
                                  })
        self.button_news.bind(on_press=self.on_press_news)
        self.settings_buttons.add_widget(self.button_news)
        if self.news_status:
            self.start_news_flasher()

        self.fees_layout = BoxLayout(orientation='horizontal',
                                     padding=[10, 0, 10, 0])
        self.fees_label = Label(text='',
                                pos_hint={
                                    'center_x': .9,
                                    'center_y': .9
                                },
                                size_hint=(0.1, 0.1))
        self.update_fees_label()
        self.fees_layout.add_widget(self.fees_label)

        self.fees_up = Button(text='+',
                              pos_hint={
                                  'center_x': .9,
                                  'center_y': .9
                              },
                              size_hint=(0.03, 0.1))
        self.fees_up.bind(on_press=self.on_press_fees_up)
        self.fees_layout.add_widget(self.fees_up)

        self.fees_down = Button(text='-',
                                pos_hint={
                                    'center_x': .9,
                                    'center_y': .9
                                },
                                size_hint=(0.03, 0.1))
        self.fees_down.bind(on_press=self.on_press_fees_down)
        self.fees_layout.add_widget(self.fees_down)

        self.fees_window = Popup(title='Fees',
                                 size_hint=(0.5, 0.5),
                                 background_color=[1, 1, 1, .5],
                                 content=self.fees_layout)
        self.button_fees = Button(text='Fees',
                                  pos_hint={
                                      'center_x': .5,
                                      'center_y': .5
                                  })
        self.button_fees.bind(on_press=self.on_press_fees)
        self.settings_buttons.add_widget(self.button_fees)

        self.button_about = Button(text='About',
                                   pos_hint={
                                       'center_x': .5,
                                       'center_y': .5
                                   })
        self.button_about.bind(on_press=self.on_press_about)
        self.settings_buttons.add_widget(self.button_about)

        self.popup_settings.add_widget(self.settings_buttons)

        self.set_display_mode(None, load_up=True)
        self.reset_pnl()  # for display mode text
        self.update_symbol_label()  # set up label

        return self.main_layout

    def load_user_data(self):
        """
        loads caches user data from last run
        """
        if self.store.exists(self._DEF_DATAJSON_NAME):
            try:
                data = self.store.get(self._DEF_DATAJSON_NAME)
                self._DEF_SYM = data['_SYM']
                self._DEF_DISP_MODE = data['_DEF_DISP_MODE']
                self._DEFAULT_NEWS_MODE = data['_DEFAULT_NEWS_MODE']
                self._DEFAULT_FEES = data['_DEFAULT_FEES']
                self._DEF_CUM_PNL = data['cum_pnl']
            except KeyError:
                pass  # no data will be loaded

        self.apply_user_data()

    def apply_user_data(self):
        """
        applies default / loaded settings to current run
        """
        self.current_symbol = self._DEF_SYM
        self.current_display_mode = self._DEF_DISP_MODE
        self.news_status = self._DEFAULT_NEWS_MODE
        self.user_fees = self._DEFAULT_FEES
        self.cumulative_pnl = self._DEF_CUM_PNL

    def save_user_data(self, *args):
        """
        save current data
        """
        self.store.put(self._DEF_DATAJSON_NAME,
                       _SYM=self.current_symbol,
                       _DEF_DISP_MODE=self.current_display_mode,
                       _DEFAULT_NEWS_MODE=self.news_status,
                       _DEFAULT_FEES=self.user_fees,
                       cum_pnl=self.cumulative_pnl)

    def start_news_flasher(self):
        """
        will be triggered upon button press and at launch
        """
        Thread(target=self.news_fetcher.news_manager,
               args=(self.flash_news, self.news_status),
               daemon=True).start()

    def reset_news_label(self):
        """
        set back to empty text after newsflash is over
        """
        self.news_label.text = ''

    def flash_news(self, text):
        """
        display a newsflash
        """
        def_y_pos = self.news_label.pos[1]
        pos = 5000
        counter = 2 * pos
        self.news_label.pos = (pos, def_y_pos)
        self.news_label.text = text
        while counter > 0 and self.news_status:
            pos -= 1.5
            counter -= 1
            self.news_label.pos = (pos, def_y_pos)
            sleep(0.01)
        self.reset_news_label()

    def set_display_mode(self, instance, load_up=False):
        """
        sets 0 for dark mode, 1 for light mode
        """

        if not load_up:
            self.current_display_mode = 0 if self.current_display_mode else 1

        self.button_display_mode.text = self.display_mode_mapping[
            self.current_display_mode]

        with self.main_layout.canvas.before:

            if self.current_display_mode == 1:
                Color(self._LIGHT_MODE_RGB)
                self.button_refresh.background_normal = 'icons/light_mode/refresh_icon_light.png'
                self.button_refresh.background_down = 'icons/light_mode/refresh_icon_light.png'
                self.button_settings.background_normal = 'icons/light_mode/settings_icon_light.png'
                self.button_settings.background_down = 'icons/light_mode/settings_icon_light.png'
                Rectangle(size=(9999, 9999))
            else:
                Color(self._DARK_MODE_RGB)
                self.button_refresh.background_normal = 'icons/dark_mode/refresh_icon_dark.png'
                self.button_refresh.background_down = 'icons/dark_mode/refresh_icon_dark.png'
                self.button_settings.background_normal = 'icons/dark_mode/settings_icon_dark.png'
                self.button_settings.background_down = 'icons/dark_mode/settings_icon_dark.png'
                self.main_layout.canvas.before.clear()

        self.entry_price_label.color = self._TEXT_COLOR_LIGHTMODE if self.current_display_mode else \
            self._TEXT_COLOR_DARKMODE
        self.news_label.color = self._TEXT_COLOR_LIGHTMODE if self.current_display_mode else \
            self._TEXT_COLOR_DARKMODE

        if self.pnl_label.text == self.zero_pnl:  # if zero pnl
            self.pnl_label.color = self._TEXT_COLOR_LIGHTMODE if self.current_display_mode else \
                self._TEXT_COLOR_DARKMODE
        self.update_cum_pnl_label()
        self.update_position_label()

    def start_ticker(self, symbol: str):
        """
        start a new ticker on a new thread
        * fetches all tickers and verifies symbol exists
        * passes `self.on_price_update` as the callback method
        """
        if symbol.upper() in self.price_fetcher.get_all_symbols():
            Thread(target=self.price_fetcher.connect_ws,
                   args=(symbol, self.on_price_update),
                   daemon=True).start()
            while not self.last_price:
                sleep(0.05)
        else:
            raise Exception(f"ticker {symbol} does not exist")

    def stop_ticker(self, symbol: str):
        """
        stop ticker (kill stream and thread)
        """
        self.price_fetcher.disconnect_ws(symbol)

    def change_ticker(self, instance, new_symbol: str):
        """
        disconnects old symbol stream and connects a new one
        uses first fetch via REST for illiquid pairs
        """
        self.stop_ticker(self.current_symbol)
        self.reset_pnl()
        self.reset_position()

        self.current_symbol = new_symbol
        self.update_symbol_label()
        self.start_ticker(new_symbol)
        self.main_symbol_button.text = new_symbol

    def on_press_news(self, instance):
        """
        enable / disable newsflash
        """
        self.news_status = not self.news_status
        if not self.news_status:
            self.news_fetcher.turn_off()
        else:
            self.start_news_flasher()
        self.button_news.text = self.generate_news_button_text()

    def generate_news_button_text(self):
        """
        generate label for news toggler based on status
        """
        return f'Display news - {self.news_status}'

    def update_fees_label(self):
        """
        update fees button label
        """
        self.user_fees = round(self.user_fees, 2)
        self.fees_label.text = f"{self.user_fees}"

    def on_press_fees(self, instance):
        """
        Open `about` popup window
        """
        self.fees_window.open()

    def on_press_fees_up(self, instance):
        """
        increments fees and updates label
        """
        self.user_fees += 0.01
        self.update_fees_label()

    def on_press_fees_down(self, instance):
        """
        decrements fees and updates label
        """
        self.user_fees -= 0.01
        self.update_fees_label()

    def on_press_about(self, instance):
        """
        Open `fees` popup window
        """
        self.about_window.open()

    @staticmethod
    def on_ref_press(*args):
        """
        open ref link
        """
        webbrowser.open(args[1])

    def on_press_sell(self, instance):
        """
        if no pos - enter short
        if long - close pos
        """
        if self.current_position == 0:
            self.current_position = -1
            self.entry_price = self.last_price

        elif self.current_position == 1:
            self.reset_position()

        self.update_status_labels()

    def on_press_buy(self, instance):
        """
        if no pos - enter long
        if short - close pos
        """
        if self.current_position == 0:
            self.current_position = 1
            self.entry_price = self.last_price

        elif self.current_position == -1:
            self.reset_position()

        self.update_status_labels()

    def on_press_refresh(self, instance):
        """
        when pressing refresh button
        """
        self.reset_cum_pnl()

    def on_press_settings(self, instance):
        """
        when pressing settings button
        """
        self.open_settings_menu()

    def open_settings_menu(self):
        """
        opens the settings popup menu
        """
        self.popup_settings.open()

    def apply_fees(self):
        """
        apply fees to pnl
        """
        self.current_pnl -= self.user_fees

    def reset_cum_pnl(self):
        """
        resets cumulative pnl
        """
        self.cumulative_pnl = 0.0
        self.update_cum_pnl_label()

    def update_status_labels(self):
        """
        updates:
        * entry price label
        * position label
        * cumulative pnl label
        """
        self.update_entry_label()
        self.update_position_label()
        self.update_cum_pnl_label()

    def reset_position(self):
        """
        * updates cumulative pnl (with fees)
        * resets position status
        * resets entry price
        * resets pos pnl
        """
        self.cumulative_pnl += (self.current_pnl - self.user_fees)
        self.current_position = 0
        self.entry_price = 0
        self.reset_pnl()
        self.update_position_label()
        self.update_entry_label()

    def reset_pnl(self):
        """Reset pnl label"""
        self.pnl_label.text = self.zero_pnl
        self.pnl_label.color = self._TEXT_COLOR_LIGHTMODE if self.current_display_mode else self._TEXT_COLOR_DARKMODE

    def on_price_update(self, price):
        """
        will be passed as callback to ws stream
        """
        self.update_pnl(price)
        precision = self.price_fetcher.get_symbol_precision(
            self.current_symbol)
        self.price_label.text = f'{price:.{precision}f}'
        if price > self.last_price:
            self.price_label.color = get_color_from_hex(self._GREEN_HEX)
        else:
            self.price_label.color = get_color_from_hex(self._RED_HEX)

        self.last_price = price

    def update_pnl(self, price):
        """
        calculates current position PnL and updates the label accordingly
        takes user fees into account
        """
        if self.current_position != 0:
            self.current_pnl = (self.entry_price / price)
            self.current_pnl = (self.current_pnl - 1) * 100 if self.current_position == -1 else \
                (1 - self.current_pnl) * 100
            self.apply_fees()

            self.pnl_label.text = f'{self.current_pnl:.{self._PNL_PERC}f}%'
            if self.current_pnl > 0:
                self.pnl_label.color = get_color_from_hex(self._GREEN_HEX)
            elif self.current_pnl < 0:
                self.pnl_label.color = get_color_from_hex(self._RED_HEX)
            else:
                self.reset_pnl()

    def update_symbol_label(self):
        """
        Updates the entry price label
        """
        self.symbol_label.text = self.current_symbol

    def update_entry_label(self):
        """
        Updates the entry price label
        """
        precision = self.price_fetcher.get_symbol_precision(
            self.current_symbol)
        self.entry_price_label.text = f'{self.entry_price:.{precision}f}'

    def update_position_label(self):
        """
        Updates current position label
        """
        self.pos_str_label.text = self.position_mapping[self.current_position]
        if self.current_position > 0:
            self.pos_str_label.color = get_color_from_hex(self._GREEN_HEX)
        elif self.current_position < 0:
            self.pos_str_label.color = get_color_from_hex(self._RED_HEX)
        else:
            self.pos_str_label.color = self._TEXT_COLOR_LIGHTMODE if self.current_display_mode else \
                self._TEXT_COLOR_DARKMODE

    def update_cum_pnl_label(self):
        """
        Updates cumulative PNL label
        """
        self.cum_pnl_label.text = f"{round(self.cumulative_pnl, 2)}%"
        if self.cumulative_pnl > 0:
            self.cum_pnl_label.color = get_color_from_hex(self._GREEN_HEX)
        elif self.cumulative_pnl < 0:
            self.cum_pnl_label.color = get_color_from_hex(self._RED_HEX)
        else:
            self.cum_pnl_label.color = self._TEXT_COLOR_LIGHTMODE if self.current_display_mode \
                else self._TEXT_COLOR_DARKMODE
        self.save_user_data()
Beispiel #29
0
class BeautyDeepApp(MDApp):
    '''Contains main interface and application logic'''
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.store = JsonStore('config.json')
        if not self.store:
            self.store['user_config'] = {
                'theme_style': 'Light',
                'theme_color': 'Pink',
                'app_language': 1,
                'public_ip': 'http://192.168.0.102:5000'
            }
        self.language = self.store['user_config']['app_language']
        self.server_ip = self.store['user_config']['public_ip']
        self.APP_ROOT = os.path.abspath('')
        self.DCIM = self.get_dcim_path()

    def build(self):
        '''Prepares the application configurations and adds all content to the screens'''
        Builder.load_file('beauty_deep.kv')
        self.theme_cls.theme_style = self.store['user_config']['theme_style']
        self.theme_cls.primary_palette = self.store['user_config'][
            'theme_color']
        self.main_interface = MainInterface()
        self.main_interface.set_toolbar_color(self.theme_cls.primary_color)
        self.change_language(self.language)
        self.main_interface.beauty_screen.add_content()
        self.main_interface.settings_screen.create_language_menu()
        return self.main_interface

    def on_start(self):
        '''Called when the app starts'''
        # self.fps_monitor_start()
        if platform == 'android':
            from android.permissions import request_permissions, Permission
            request_permissions([
                Permission.INTERNET, Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE
            ])

    def on_pause(self):
        '''Called when the app is on pause'''
        return True

    def on_resume(self):
        '''Called when the app is resume'''
        pass

    def on_stop(self):
        '''Called when the app is stopped'''
        try:
            os.remove('output.jpg')
            os.remove('mask-output.jpg')
        except:
            pass

    def get_dcim_path(self):
        '''Gets gallery directory path'''
        if platform == 'android':
            return storagepath.get_pictures_dir()
        else:
            return self.APP_ROOT

    def switch_theme_style(self):
        '''Changes the theme style of the application'''
        if self.theme_cls.theme_style == 'Dark':
            self.theme_cls.theme_style = 'Light'
            self.store.put('user_config',
                           theme_style='Light',
                           theme_color=self.theme_cls.primary_palette,
                           app_language=self.language,
                           public_ip=self.server_ip)
        else:
            self.theme_cls.theme_style = 'Dark'
            self.store.put('user_config',
                           theme_style='Dark',
                           theme_color=self.theme_cls.primary_palette,
                           app_language=self.language,
                           public_ip=self.server_ip)

    def switch_theme_color(self, color_name):
        '''Changes the theme color of the application'''
        self.theme_cls.primary_palette = color_name
        self.store.put('user_config',
                       theme_style=self.theme_cls.theme_style,
                       theme_color=color_name,
                       app_language=self.language,
                       public_ip=self.server_ip)

    def change_language(self, language):
        '''Changes the interface language of the entire app'''
        self.language = language
        self.store.put('user_config',
                       theme_style=self.theme_cls.theme_style,
                       theme_color=self.theme_cls.primary_palette,
                       app_language=language,
                       public_ip=self.server_ip)
        self.main_interface.home_screen.add_content(self.language)
        self.main_interface.settings_screen.light_label.text = languages[
            self.language]['light']
        self.main_interface.settings_screen.dark_label.text = languages[
            self.language]['dark']
        self.main_interface.settings_screen.style_label.text = languages[
            self.language]['theme_style']
        self.main_interface.settings_screen.color_label.text = languages[
            self.language]['theme_color']
        self.main_interface.settings_screen.language_label.text = languages[
            self.language]['choose_language']
        self.main_interface.settings_screen.lang_chooser.text = languages[
            self.language]['lang']
        self.main_interface.settings_screen.server_label.text = languages[
            self.language]['server']
        self.main_interface.settings_screen.about_label.text = languages[
            self.language]['about_us']
        self.main_interface.settings_screen.developer_label.text = languages[
            self.language]['developer']
        self.main_interface.settings_screen.feedback_label.text = languages[
            self.language]['feedback']
        self.main_interface.settings_screen.social_label.text = languages[
            self.language]['social']
        self.main_interface.settings_screen.share_label.text = languages[
            self.language]['share']
        self.main_interface.settings_screen.rate_label.text = languages[
            self.language]['rate']
        self.main_interface.spinner_screen.processing_label1.text = languages[
            self.language]['image_processing1']
        self.main_interface.spinner_screen.processing_label2.text = languages[
            self.language]['image_processing2']
        self.main_interface.beauty_screen.save_button.text = languages[
            self.language]['save_results']
        self.main_interface.beauty_screen.mask_button.text = languages[
            self.language]['hide_mask']

    def change_server_ip(self, ip):
        '''Changes server public ip (http://ip:port)'''
        self.server_ip = ip
        self.store.put('user_config',
                       theme_style=self.theme_cls.theme_style,
                       theme_color=self.theme_cls.primary_palette,
                       app_language=self.language,
                       public_ip=ip)

    def file_manager_open(self):
        '''Call plyer filechooser API to run a filechooser activity in given directory'''
        filechooser.open_file(path=self.DCIM,
                              preview=True,
                              filters=[('Images', '*.jpg', '*.png', '*.svg',
                                        '*.bmp', '*.eps', '*.eic')],
                              on_selection=self.select_path)

    def select_path(self, selection):
        '''Callback function for handling the selection response from activity.
		Selects a file, launch a spinner and starts image processing in a separate thread'''
        if selection:
            path = selection[0]
            if path[-3:].lower() not in [
                    'jpg', 'png', 'svg', 'bmp', 'eps', 'eic'
            ]:
                toast(languages[self.language]['unsupported_format'])
            else:
                self.main_interface.current = 'spinner_screen'
                self.main_interface.beauty_screen.image_path = path
                Thread(target=self.get_faces).start()

    def set_current_screen(self, screen, *, with_reset=True):
        '''Goes to the specified screen. 
		Param with_reset resets BeautyScreen by default and deletes temporary images'''
        self.main_interface.current = screen
        if with_reset and self.main_interface.beauty_screen.image_path:
            try:
                os.remove('output.jpg')
                os.remove('mask-output.jpg')
            except:
                pass
            self.main_interface.beauty_screen.image_path = None
            self.main_interface.beauty_screen.input_image = None
            self.main_interface.beauty_screen.image_viewer = None
            self.main_interface.beauty_screen.mask_button.text = languages[
                self.language]['hide_mask']

    def get_faces(self):
        '''Recognizes and processes the image with a neural network and goes to the BeautyScreen'''
        try:
            im = Image(self.main_interface.beauty_screen.image_path)
            self.main_interface.beauty_screen.input_image = im.image.copy()
            im.send_request(self.server_ip)
            im.create_output(mask=False)
            im.create_output(mask=True)
            self.main_interface.beauty_screen.set_image('mask-output.jpg')
            self.main_interface.beauty_screen.set_beauty_params(im.faces[0], 0)
            self.main_interface.beauty_screen.faces = im.faces
            self.main_interface.beauty_screen.create_face_menu()
            self.main_interface.current = 'beauty_screen'
        except ValueError:
            toast(languages[self.language]['small_resolution'])
            self.set_current_screen('menu_screen')
        except ConnectionError:
            toast(languages[self.language]['server_off'])
            self.set_current_screen('menu_screen')
        except Exception as e:
            print(e)
            toast(languages[self.language]['not_recognized'])
            self.set_current_screen('menu_screen')
	def saverecordedpositions(self,filename):
		postionsstore = JsonStore(filename +'.json')
		postionsstore.put('3dpostions_list', postionvalues = self.recordedpositions)
Beispiel #31
0
class Controller(EventDispatcher):
    """
    Controls the playing of audio and coordinates the updating of the playlist
    and screen displays
    """
    volume = NumericProperty(1.0)
    advance = True
    # This flag indicates whether to advance to the next track
    # once the currently playing one had ended

    sm = None  # THe ScreenManager
    pos = 0

    def __init__(self, **kwargs):
        """ Initialize the screens and the screen manager """
        self._store = JsonStore(
            join(self._get_settings_folder(), "zenplayer.json"))
        self.playlist = PlayList(self._store)

        self.sm = ScreenManager()
        self.playing = PlayingScreen(self, name="main")
        self.sm.add_widget(self.playing)
        self.sm.current = "main"

        if platform not in ['ios', 'android']:
            self.kb_listener = ZenKeyboardListener(self.on_key_down,
                                                   self.playing)
        Sound.add_state_callback(self.playing.on_sound_state)
        Sound.add_state_callback(self._on_sound_state)

        super(Controller, self).__init__(**kwargs)
        if self._store.exists('state'):
            state = self._store.get("state")
            if "volume" in state.keys():
                self.volume = state["volume"]

    @staticmethod
    def _get_settings_folder():
        """ Return the folder when the setting file is stored. """
        path = expanduser("~/.zencode")
        if not exists(path):
            mkdir(path)
        return path

    def _on_sound_state(self, state):
        """ The sound state has changed. If the track played to the end,
        move to the next track."""
        if state == "finished" and self.advance:
            self.play_next()

    def get_current_art(self):
        return self.playlist.get_current_art()

    def get_current_info(self):
        return self.playlist.get_current_info()

    def get_current_file(self):
        return self.playlist.get_current_file()

    @staticmethod
    def get_pos_length():
        return Sound.get_pos_length()

    def on_key_down(self, keyboard, keycode, text, modifiers):
        """ React to the keypress event """
        key_name = keycode[1]
        if key_name == "up" or text == "+":
            self.volume += 0.025
        elif key_name == "down" or text == "-":
            self.volume -= 0.025
        elif key_name == "x":
            self.play_pause()
        elif key_name == "z":
            self.play_previous()
        elif key_name == "v":
            self.stop()
        elif key_name == "b":
            self.play_next()
        elif key_name == "a":
            self.show_filebrowser()
        elif key_name == "p":
            self.show_playlist()
        elif key_name == "s":
            self.show_main()

        return True

    def on_volume(self, widget, value):
        """ Set the volume of the currently playing sound """
        if 0.0 > value:
            self.volume = 0.0
        elif value > 1.0:
            self.volume = 1.0
        else:
            Sound.set_volume(value)
            self.playing.volume_slider.value = value

    def play_index(self, index):
        """
        Play the track with the specified playlist index
        """
        Sound.stop()
        self.playlist.current = index
        self.play_pause()

    def play_pause(self):
        """ Play or pause the currently playing track """
        self.advance = True
        if Sound.state == "playing":
            self.pos, x = Sound.get_pos_length()
            Sound.stop()
        else:
            audio_file = self.get_current_file()
            if audio_file:
                Sound.play(audio_file, self.volume)
                if self.pos > 0:

                    def set_pos(dt):
                        Sound.seek(self.pos)
                        self.pos = 0

                    Clock.schedule_once(set_pos, 0.1)

    def play_next(self):
        """ Play the next track in the playlist. """

        Sound.stop()
        self.playlist.move_next()
        self.play_pause()

    def play_previous(self):
        """ Play the previous track in the playlist. """
        Sound.stop()
        self.playlist.move_previous()
        self.play_pause()

    @staticmethod
    def set_position(value):
        """ Set the playing position to the specified value. """
        Sound.set_position(value)

    def save(self):
        """ Save the state of the the playlist and volume. """
        self.playlist.save(self._store)
        self._store.put("state", volume=self.volume)
        if "filebrowser" in self.sm.screen_names:
            self.sm.get_screen("filebrowser").save(self._store)

    def show_filebrowser(self):
        """ Switch to the file browser screen """
        if "filebrowser" not in self.sm.screen_names:
            self.sm.add_widget(
                ZenFileBrowser(self,
                               self.playlist,
                               self._store,
                               name="filebrowser"))
        self.sm.current = "filebrowser"

    def show_playlist(self):
        """ Switch to the playlist screen """
        if "playlist" not in self.sm.screen_names:
            self.sm.add_widget(
                PlayListScreen(self.sm, self, self.playlist, name="playlist"))
        self.sm.current = "playlist"

    def show_main(self):
        """ Switch to the main playing screen"""
        self.sm.current = "main"

    def stop(self):
        """ Stop any playing audio """
        self.advance = False
        Sound.stop()
Beispiel #32
0
class MainApp(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.theme_cls.theme_style = "Light"
        self.theme_cls.primary_palette = "Teal"

        self.storage = JsonStore('../store.json')
        self.emails = JsonStore('../emails.json')

        self.view_stock_widgets = []
        self.manage_items_widgets = []
        self.add_remove_stock_widgets = []
        self.edit_item_widgets = []
        self.send_data_widgets = []
        self.low_stock_widgets = []

    def add_item(self, name, stock_type, stock_level, stock_units,
                 low_threshold, pop_weighting):
        inputs = [
            name, stock_type, stock_level, stock_units, low_threshold,
            pop_weighting
        ]
        if '' not in inputs:
            self.storage.put(name,
                             name=name,
                             stock_type=stock_type,
                             stock_level=int(stock_level),
                             stock_units=stock_units,
                             low_threshold=int(low_threshold),
                             pop_weighting=int(pop_weighting))
        else:
            toast('Some fields were left blank...')

    def remove_item(self, name):
        self.storage.delete(name)

    def remove_email(self, email):
        self.emails.delete(email)

    def update_stock_level(self, name, stock_level_change):
        item = self.storage.get(name)
        item['stock_level'] += stock_level_change
        if item['stock_level'] < 0:
            item['stock_level'] = 0
        self.storage.put(name,
                         name=name,
                         stock_type=item['stock_type'],
                         stock_level=item['stock_level'],
                         stock_units=item['stock_units'],
                         low_threshold=item['low_threshold'],
                         pop_weighting=item['pop_weighting'])

    def apply_stock_changes(self):
        for widget in self.add_remove_stock_widgets:
            try:
                if widget.ids.plus_minus.active == True:
                    sign = '+'
                else:
                    sign = '-'
            except AttributeError:
                continue
            if len(widget.ids.stock.text) > 0:
                stock_change = sign + widget.ids.stock.text
                self.update_stock_level(widget.ids.name.text,
                                        int(stock_change))
                widget.ids.stock.text = ''
        self.load_add_remove_stock_screen()
        self.load_low_stock_screen()
        toast('Update Successful')

    def apply_edit_changes(self, name, stock_type, stock_level, stock_units,
                           low_threshold, pop_weighting):
        self.storage.delete(self.editing_item)
        self.storage.put(name,
                         name=name,
                         stock_type=stock_type,
                         stock_level=int(stock_level),
                         stock_units=stock_units,
                         low_threshold=int(low_threshold),
                         pop_weighting=int(pop_weighting))
        self.load_manage_items_screen()
        self.load_view_stock_screen()
        self.load_add_remove_stock_screen()
        self.load_low_stock_screen()
        self.editing_item = None
        toast('Changes Applied')

    def delete_item(self, item):
        screen = self.root.ids.screen_manager.current
        if screen == 'manage_items':
            self.remove_item(item)
            self.root.ids.screen_manager.current = 'manage_items'
            self.load_manage_items_screen()
            self.load_view_stock_screen()
            self.load_add_remove_stock_screen()
            self.load_low_stock_screen()
        elif screen == 'send_data':
            self.remove_email(item)
            self.root.ids.screen_manager.current = 'send_data'
            self.load_send_data_screen()
        toast('Deleted')

    def load_manage_items_screen(self):
        for widget in self.manage_items_widgets:
            self.root.ids.manage_items_list.remove_widget(widget)
        keys = sorted(self.storage.keys())
        stock_types = []
        for key in self.storage:
            item = self.storage.get(key)
            if item['stock_type'] not in stock_types:
                stock_types.append(item['stock_type'])
        stock_types.sort()
        for stock_type in stock_types:
            widget = Subtitle_Widget(stock_type)
            self.root.ids.manage_items_list.add_widget(widget)
            self.manage_items_widgets.append(widget)
            for key in keys:
                item = self.storage.get(key)
                if item['stock_type'] == stock_type:
                    name = item['name']
                    widget = Manage_Items_Swipe_Card(name)
                    self.root.ids.manage_items_list.add_widget(widget)
                    self.manage_items_widgets.append(widget)

    def load_view_stock_screen(self):
        for widget in self.view_stock_widgets:
            self.root.ids.view_stock_list.remove_widget(widget)
        keys = sorted(self.storage.keys())
        stock_types = []
        for key in self.storage:
            item = self.storage.get(key)
            if item['stock_type'] not in stock_types:
                stock_types.append(item['stock_type'])
        stock_types.sort()
        for stock_type in stock_types:
            widget = Subtitle_Widget(stock_type)
            self.root.ids.view_stock_list.add_widget(widget)
            self.view_stock_widgets.append(widget)
            for key in keys:
                item = self.storage.get(key)
                if item['stock_type'] == stock_type:
                    name = item['name']
                    stock_level = item['stock_level']
                    units = item['stock_units']
                    low_threshold = item['low_threshold']
                    if stock_level <= low_threshold:
                        low = True
                    else:
                        low = False
                    stock_level_string = str(stock_level) + ' ' + str(units)
                    widget = View_Stock_Card(name, stock_level_string, low)
                    self.root.ids.view_stock_list.add_widget(widget)
                    self.view_stock_widgets.append(widget)

    def load_add_remove_stock_screen(self):
        for widget in self.add_remove_stock_widgets:
            self.root.ids.add_remove_stock_list.remove_widget(widget)
        self.add_remove_stock_widgets = []
        keys = sorted(self.storage.keys())
        stock_types = []
        for key in self.storage:
            item = self.storage.get(key)
            if item['stock_type'] not in stock_types:
                stock_types.append(item['stock_type'])
        stock_types.sort()
        for stock_type in stock_types:
            widget = Subtitle_Widget(stock_type)
            self.root.ids.add_remove_stock_list.add_widget(widget)
            self.add_remove_stock_widgets.append(widget)
            for key in keys:
                item = self.storage.get(key)
                if item['stock_type'] == stock_type:
                    name = item['name']
                    widget = Add_Remove_Stock_Card(name)
                    self.root.ids.add_remove_stock_list.add_widget(widget)
                    self.add_remove_stock_widgets.append(widget)
        widget = MDCard(size_hint_y=None, height='50dp')
        self.root.ids.add_remove_stock_list.add_widget(widget)
        self.add_remove_stock_widgets.append(widget)

    def load_edit_item_screen(self, key):
        for widget in self.edit_item_widgets:
            self.root.ids.edit_item_layout.remove_widget(widget)
        self.edit_item_widgets = []
        item = self.storage.get(key)
        widget = Edit_Item_Dialog_Content()
        widget.ids.item_name.text = str(item['name'])
        widget.ids.item_type.text = str(item['stock_type'])
        widget.ids.stock_level.text = str(item['stock_level'])
        widget.ids.stock_units.text = str(item['stock_units'])
        widget.ids.low_threshold.text = str(item['low_threshold'])
        widget.ids.pop_weighting.text = str(item['pop_weighting'])
        self.root.ids.edit_item_layout.add_widget(widget)
        self.edit_item_widgets.append(widget)
        self.editing_item = item['name']

    def load_send_data_screen(self):
        for widget in self.send_data_widgets:
            self.root.ids.emails_list.remove_widget(widget)
        self.send_data_widgets = []
        keys = sorted(self.emails.keys())
        for key in keys:
            email = self.emails.get(key)
            widget = Email_Contact_Card(email['email'])
            self.root.ids.emails_list.add_widget(widget)
            self.send_data_widgets.append(widget)

    def load_low_stock_screen(self):
        for widget in self.low_stock_widgets:
            self.root.ids.low_stock_layout.remove_widget(widget)
        self.low_stock_widgets = []
        keys = sorted(self.storage.keys())
        stock_types = []
        for key in self.storage:
            item = self.storage.get(key)
            if item['stock_type'] not in stock_types:
                stock_types.append(item['stock_type'])
        stock_types.sort()
        for stock_type in stock_types:
            widget = Subtitle_Widget(stock_type)
            self.root.ids.low_stock_layout.add_widget(widget)
            self.low_stock_widgets.append(widget)
            for key in keys:
                item = self.storage.get(key)
                if item['stock_type'] == stock_type and item[
                        'stock_level'] <= item['low_threshold']:
                    widget = Low_Stock_Item_Card(item['name'])
                    self.root.ids.low_stock_layout.add_widget(widget)
                    self.low_stock_widgets.append(widget)

    def open_add_item_popup(self):
        content = Add_Item_Dialog_Content()
        self.popup = MDDialog(
            type='custom',
            content_cls=content,
            auto_dismiss=False,
        )
        self.popup.open()

    def confirm_delete_dialog(self, item):
        content = Confirm_Delete_Dialog_Content(item)
        self.popup = MDDialog(
            type='custom',
            content_cls=content,
            auto_dismiss=False,
        )
        self.popup.open()

    def open_add_email_popup(self):
        content = Add_Email_Content()
        self.popup = MDDialog(
            type='custom',
            content_cls=content,
            auto_dismiss=False,
        )
        self.popup.open()

    def add_contact(self, email):
        self.emails.put(email, email=email, sent=False)
        self.load_send_data_screen()

    def send_email(self, email):

        address = self.emails.get(email)
        self.emails.put(email, email=email, sent=True)

        #customise frm and password to send emails from your account for testing purposes.
        frm = '*****@*****.**'
        password = ''
        to = email
        subject = 'Stock Level Data'

        server = smtplib.SMTP(host='smtp.gmail.com', port=587)
        server.starttls()
        server.login(frm, password)

        msg = MIMEMultipart()
        msg['From'] = frm
        msg['to'] = to
        msg['subject'] = subject

        body = ""

        keys = self.storage.keys()
        keys.sort()

        stock_types = []
        for key in keys:
            stock_type = self.storage.get(key)['stock_type']
            if stock_type not in stock_types:
                stock_types.append(stock_type)
        for stock_type in stock_types:
            body += '%s\n' % stock_type.upper()
            for key in keys:
                item = self.storage.get(key)
                if item['stock_type'] == stock_type:
                    body += '%s: %s %s\n' % (item['name'], item['stock_level'],
                                             item['stock_units'])
            body += '\n'

        msg.attach(MIMEText(body, 'plain'))

        server.sendmail(frm, to, msg.as_string())

        toast('Sent to: %s' % email)

    def set_screen(self, screen):
        self.root.ids.screen_manager.current = screen

    def build(self):
        self.title = 'WTF Stock Take'
        return MainLayout()

    def on_start(self):
        self.load_manage_items_screen()
        self.load_view_stock_screen()
        self.load_add_remove_stock_screen()
        self.load_send_data_screen()
        self.load_low_stock_screen()
Beispiel #33
0
class DataBase:
    url = 'https://ospapp-53708.firebaseio.com/.json?auth='
    admin_passwd = ''

    def __init__(self, path, heroes_path, passwd_path):
        self.path = path
        self.store = JsonStore(path)
        with open("secret", 'r') as file:
            data = file.read().split("\n")
            self.url = self.url + data[0]
        self.firebase_patch_all()
        try:
            string = str(requests.get(self.url).json()['heroes'])
            if string:
                with open(heroes_path, 'w') as file:
                    file.write(string)
        except Exception as e:
            print(str(e))
        try:
            with open(heroes_path, 'r') as file:
                self.heroes = json.loads(str(file.read()).replace("'", '"'))
        except Exception as e:
            print(str(e))
            self.heroes = ["brak strażaków w bazie"]
        try:
            string = str(requests.get(self.url).json()['passwd'])
            if string:
                with open(passwd_path, 'w') as file:
                    file.write(string)
        except Exception as e:
            print(str(e))
        try:
            with open(passwd_path, 'r') as file:
                global admin_passwd
                admin_passwd = file.readline()
        except Exception as e:
            print(str(e))

    def put_report(self, uuid_num, id_number, dep_date, dep_time, spot_time,
                   location, type_of_action, section_com, action_com, driver,
                   perpetrator, victim, section, details, return_date,
                   end_time, home_time, stan_licznika, km_location, completed):
        if uuid_num == "":
            uuid_num = str(uuid.uuid1())
        if section_com == "Dowódca sekcji":
            section_com = ""
        if action_com == "Dowódca akcji":
            action_com = ""
        if driver == "Kierowca":
            driver = ""
        self.store.put(uuid_num,
                       innerID=id_number,
                       depDate=dep_date,
                       depTime=dep_time,
                       spotTime=spot_time,
                       location=location,
                       type=type_of_action,
                       sectionCom=section_com,
                       actionCom=action_com,
                       driver=driver,
                       perpetrator=perpetrator,
                       victim=victim,
                       section=section,
                       details=details,
                       returnDate=return_date,
                       endTime=end_time,
                       homeTime=home_time,
                       stanLicznika=stan_licznika,
                       KM=km_location,
                       modDate=self.get_date(),
                       ready=completed)
        try:
            string = "{'" + uuid_num + "': " + str(
                self.store.get(uuid_num)) + "}"
            to_database = json.loads(string.replace("'", '"'))
            requests.patch(url=self.url, json=to_database)
        except Exception as e:
            print(str(e))

    def delete_report(self, uuid_num):
        if self.store.exists(uuid_num):
            try:
                # requests.delete(url=self.url[:-5] + id_number + ".json")
                string = '{"deleted-' + uuid_num + '": "true"}'
                to_database = json.loads(string)
                requests.patch(url=self.url, json=to_database)
            except Exception as e:
                Factory.deletePopout().open()
                print(str(e))
            else:
                self.store.delete(uuid_num)
        else:
            return -1

    def get_heroes(self):
        return self.heroes

    def firebase_patch_all(self):
        try:
            with open(self.path, 'r') as file:
                data = file.read()
                to_database = json.loads(data)
                requests.patch(url=self.url, json=to_database)
        except Exception as e:
            print(str(e))

    def delete_all(self):
        string_all = ""
        try:
            for key in self.store.keys():
                # requests.delete(url=self.url[:-5] + key + ".json")
                string = '{"deleted-' + key + '": "true"}'
                string_all = string_all + string
                to_database = json.loads(string)
                requests.patch(url=self.url, json=to_database)
        except Exception as e:
            Factory.deletePopout().open()
            print(str(e))
        else:
            self.store.clear()

    def get_report(self, id_number):
        for item in self.store.find(innerID=id_number):
            dane = self.store.get(item[0])
            id_number = dane['innerID']
            dep_date = dane['depDate']
            dep_time = dane['depTime']
            spot_time = dane['spotTime']
            location = dane['location']
            type_of_action = dane['type']
            section_com = dane['sectionCom']
            action_com = dane['actionCom']
            driver = dane['driver']
            perpetrator = dane['perpetrator']
            victim = dane['victim']
            section = dane['section']
            details = dane['details']
            return_date = dane['returnDate']
            end_time = dane['endTime']
            home_time = dane['homeTime']
            stan_licznika = dane['stanLicznika']
            km_location = dane['KM']
            date = dane['modDate']
            completed = dane['ready']
            return [
                item[0], id_number, dep_date, dep_time, spot_time, location,
                type_of_action, section_com, action_com, driver, perpetrator,
                victim, section, details, return_date, end_time, home_time,
                stan_licznika, km_location, date, completed
            ]
        else:
            return -1

    def get_all_friendly(self):
        result = []
        for item in self.store.keys():
            data = self.store.get(item)
            result.append(data["innerID"] + " " + data["location"])
        return result

    def find_inner_id(self, id_number):
        for _ in self.store.find(innerID=id_number):
            return True
        return False

    @staticmethod
    def get_date():
        return str(datetime.datetime.now()).split(".")[0]

    def get_passwd(self):
        global admin_passwd
        return admin_passwd
Beispiel #34
0
	def updata_say_text_list(self,text_list):
		store = JsonStore('tts.json')
		store.put('text',txt1=text_list[0],txt2=text_list[1],txt3=text_list[2],txt4=text_list[3])
	def savecalibration(self,mtx,dist):
		calibrationstore = JsonStore('Saved_calibration.json')
		lstmtx = mtx.tolist()
		lstdist = dist.tolist()
		calibrationstore.put('calibration_var', mtx = lstmtx, dist = lstdist)
Beispiel #36
0
class DownloaderApp(App):

    use_kivy_settings = False

    def on_pause(self):
        return True

    def paste(self):
        '''
        try:
            from kivy.core.clipboard import Clipboard
            self.main_screen.ids.page_url.text = Clipboard.paste()
        except:
            logger.error("Could not be pasted to clipboard!")
            pass
        '''
        pass

    def copy(self,text):
        try:
            from kivy.core.clipboard import Clipboard
            Clipboard.copy(text)
        except:
            logger.error("Could not be copied to clipboard: "+text)
            pass

    def build(self):
        self.store = JsonStore("data/store.json")
        self.download_thread = None
        self.screen_manager = ScreenManager(transition=FadeTransition())
        self.main_screen = StartScreen(name='Welcome Screen')
        self.download_screen = DownloadScreen(name="Download Screen")
        self.screen_manager.add_widget(self.main_screen)
        self.screen_manager.add_widget(self.download_screen)
        return self.screen_manager

    def target_selected(self, path, filename):
        self._popup.dismiss()
        self.main_screen.ids.target_folder.text = path
        self.store.put("target_folder",value=self.main_screen.ids.target_folder.text)

    def target_selection(self):
        content = LoadDialog(load=self.target_selected, cancel=self.dismiss_popup)
        content.ids.filechooser.path = self.main_screen.ids.target_folder.text
        self._popup = Popup(title="Choose destination", content=content, size_hint=(0.9, 0.9))
        self._popup.open()

    def dismiss_popup(self):
        self._popup.dismiss()

    def url_ready(self,page_url):
        if not self.main_screen.ids.page_url.text.startswith("http://") and not self.main_screen.ids.page_url.text.startswith("https://"):
            self.message("There is a problem...","URL is not accepted, needs an http/s url")
            return
        self.store.put("target_folder",value=self.main_screen.ids.target_folder.text)
        self.store.put("source_url",value=self.main_screen.ids.page_url.text)

        self.media_url = self.main_screen.ids.page_url.text
        self.video_title = self.media_url

        self.screen_manager.current = self.screen_manager.next()

        self.start_download()

    def start_download(self):
        logger.debug("start_download called")

        self.download_screen.result = "downloading "+self.media_url+"\n\n"

        self.target_file = os.path.join( self.main_screen.ids.target_folder.text , self.video_title.decode("utf-8") )
        self.target_folder = self.main_screen.ids.target_folder.text

        self.download_screen.ids.loading.opacity=1
        self.download_screen.ids.label_text_message.text="decoding:\n\n"+self.media_url
        progressDialog = self.download_screen.ids.progress_bar_download
        progressDialoglabel = self.download_screen.ids.label_text_message
        self.download_thread = DownloadThread(self.media_url,self.target_folder,self.download_screen,progressDialog,progressDialoglabel)
        self.download_thread.start()

    def abort_download(self):
        logger.debug("abort_download")
        try:
            self.download_thread.abort()
        except:
            pass
        self.screen_manager.current = self.screen_manager.previous()

    def message(self,title,body):

        content = MessageDialog()
        content.ids.message_body.text = body
        self._popup = Popup(title=title, content=content, size_hint=(0.8, 0.8))
        self._popup.open()

    def on_stop(self):
        logger.debug("on_stop event called: goodbye!")
Beispiel #37
0
class CalcPyApp(App):
    def build(self):
        self.store = JsonStore('scripts.json')

        self.appview = NavigationDrawer()
        self.appview.anim_type = 'reveal_below_anim'

        side_panel = BoxLayout(orientation='vertical')

        title = Label(text='Pycalc')
        title.size = self.appview.width, 30
        title.size_hint_y = None
        side_panel.add_widget(title)

        new_btn = Button(text='New Script')
        new_btn.size = self.appview.width, 50
        new_btn.size_hint_y = None
        new_btn.bind(on_press=lambda _: self.new_script())
        side_panel.add_widget(new_btn)

        s_in = TextInput()
        s_in.multiline = False
        s_in.size = self.appview.width, 50
        s_in.size_hint_y = None

        def show_s_in():
            s_in.height, s_in.opacity, s_in.disabled = 50, 1, False
            save_btn.height, save_btn.opacity, save_btn.disabled = 0, 0, True

            def focus():
                s_in.focus = True

            Clock.schedule_once(lambda dt: focus(), 0.1)

        def hide_s_in(x=False):
            if x:
                return
            s_in.height, s_in.opacity, s_in.disabled = 0, 0, True
            save_btn.height, save_btn.opacity, save_btn.disabled = 50, 1, False

        save_btn = Button(text='Save Script')
        save_btn.size = self.appview.width, 50
        save_btn.size_hint_y = None
        save_btn.bind(on_press=lambda _: show_s_in())
        side_panel.add_widget(save_btn)

        s_in.bind(on_text_validate=lambda instance: self.save_script(
            instance.text.strip()))
        s_in.bind(focused=lambda _, x: hide_s_in(x))
        hide_s_in()

        side_panel.add_widget(s_in)

        load_btn = Button(text='Load Script')
        load_btn.size = self.appview.width, 50
        load_btn.size_hint_y = None
        load_btn.bind(on_press=lambda _: self.load_script())
        side_panel.add_widget(load_btn)

        self.appview.add_widget(side_panel)

        self.main_panel = ScrollableText()
        self.appview.add_widget(self.main_panel)

        return self.appview

    def new_script(self):
        global state
        global lexer
        state = State()
        lexer.state = state
        self.main_panel.layout.clear_widgets()
        self.main_panel.add_new_codeline()

    def save_script(self, name):
        lines = []
        for wid in reversed(self.main_panel.layout.children):
            if isinstance(wid, CodeInput) and len(wid.text) > 0:
                lines.append(wid.text)

        if len(lines) > 0:
            self.store.put(name, data=lines)

    def load_script(self):
        popup = Popup(title='Load script')

        def want_delete(btn, choice_callback, _):
            def delete(name):
                self.store.delete(name)
                btn.height, btn.opacity, btn.disabled = 0, 0, True

            saved_text = btn.text
            callback = lambda _: delete(saved_text)

            def lost_focus(_):
                btn.text = saved_text
                btn.color = (1, 1, 1, 1)
                btn.unbind(on_press=callback)
                btn.bind(on_release=choice_callback)

            btn.text = 'delete?'
            btn.color = (1, 0, 0, 1)
            btn.bind(on_press=callback)
            Clock.schedule_once(lost_focus, 2)
            btn.unbind(on_release=choice_callback)

        def create_clock(widget, touch, choice_callback, *args):
            if not isinstance(widget, Button):
                return

            if not widget.collide_point(*touch.pos):
                return

            callback = partial(want_delete, widget, choice_callback)
            Clock.schedule_once(callback, 0.5)
            touch.ud['event'] = callback

        def delete_clock(widget, touch, *args):
            if not isinstance(widget, Button):
                return

            if 'event' in touch.ud:
                Clock.unschedule(touch.ud['event'])
                del touch.ud['event']

        def choice(name):
            self.new_script()

            data = self.store.get(name)['data']

            for line in data:
                codeinput = self.main_panel.layout.children[0]

                codeinput.text = line
                self.main_panel.code_interpret(codeinput)

            popup.dismiss()

        scroll_content = ScrollView()
        content = BoxLayout(orientation='vertical', size_hint_y=None)
        content.bind(minimum_height=content.setter('height'))
        scroll_content.add_widget(content)
        for item in self.store:
            btn = Button(text=item)
            btn.size = content.width, 50
            btn.size_hint_y = None

            choice_callback = lambda _: choice(item)
            btn.bind(on_touch_down=partial(create_clock,
                                           choice_callback=choice_callback),
                     on_touch_up=delete_clock)
            btn.bind(on_release=choice_callback)
            content.add_widget(btn)
        close_btn = Button(text='Cancel')
        close_btn.size_hint = 0.3, None
        close_btn.height = 50
        close_btn.bind(on_press=popup.dismiss)
        content.add_widget(close_btn)
        popup.content = scroll_content

        popup.open()
Beispiel #38
0
class KaTrainBase:
    USER_CONFIG_FILE = os.path.expanduser("~/.katrain/config.json")
    PACKAGE_CONFIG_FILE = "katrain/config.json"
    """Settings, logging, and players functionality, so other classes like bots who need a katrain instance can be used without a GUI"""
    def __init__(self, force_package_config=False, debug_level=0, **kwargs):
        self.debug_level = debug_level
        self.game = None

        self.logger = lambda message, level=OUTPUT_INFO: self.log(
            message, level)
        self.config_file = self._load_config(
            force_package_config=force_package_config)
        self.debug_level = debug_level or self.config("general/debug_level",
                                                      OUTPUT_INFO)

        Config.set("kivy", "log_level", "warning")
        if self.debug_level >= OUTPUT_DEBUG:
            Config.set("kivy", "log_enable", 1)
            Config.set("kivy", "log_level", "debug")
        if self.debug_level >= OUTPUT_EXTRA_DEBUG:
            Config.set("kivy", "log_level", "trace")
        self.players_info = {"B": Player("B"), "W": Player("W")}
        self.reset_players()

    def log(self, message, level=OUTPUT_INFO):
        if level == OUTPUT_ERROR:
            print(f"ERROR: {message}")
        elif self.debug_level >= level:
            print(message)

    def _load_config(self, force_package_config):
        if len(sys.argv) > 1 and sys.argv[1].endswith("config.json"):
            config_file = os.path.abspath(sys.argv[1])
            self.log(f"Using command line config file {config_file}",
                     OUTPUT_INFO)
        else:
            user_config_file = find_package_resource(self.USER_CONFIG_FILE)
            package_config_file = find_package_resource(
                self.PACKAGE_CONFIG_FILE)
            if force_package_config:
                config_file = package_config_file
            else:
                try:
                    if not os.path.exists(user_config_file):
                        os.makedirs(os.path.split(user_config_file)[0],
                                    exist_ok=True)
                        shutil.copyfile(package_config_file, user_config_file)
                        config_file = user_config_file
                        self.log(
                            f"Copied package config to local file {config_file}",
                            OUTPUT_INFO)
                    else:  # user file exists
                        version = JsonStore(user_config_file,
                                            indent=4).get("general")["version"]
                        if version < CONFIG_MIN_VERSION:
                            backup = user_config_file + f".{version}.backup"
                            shutil.copyfile(user_config_file, backup)
                            shutil.copyfile(package_config_file,
                                            user_config_file)
                            self.log(
                                f"Copied package config file to {user_config_file} as user file is outdated (<{CONFIG_MIN_VERSION}). Old version stored as {backup}",
                                OUTPUT_INFO,
                            )
                        config_file = user_config_file
                        self.log(f"Using user config file {config_file}",
                                 OUTPUT_INFO)
                except Exception as e:
                    config_file = package_config_file
                    self.log(
                        f"Using package config file {config_file} (exception {e} occurred when finding or creating user config)",
                        OUTPUT_INFO,
                    )
        try:
            self._config_store = JsonStore(config_file, indent=4)
        except Exception as e:
            self.log(f"Failed to load config {config_file}: {e}", OUTPUT_ERROR)
            sys.exit(1)
        self._config = dict(self._config_store)
        return config_file

    def save_config(self, key=None):
        if key is None:
            for k, v in self._config.items():
                self._config_store.put(k, **v)
        else:
            self._config_store.put(key, **self._config[key])

    def config(self, setting, default=None):
        try:
            if "/" in setting:
                cat, key = setting.split("/")
                return self._config.get(cat, {}).get(key, default)
            else:
                return self._config[setting]
        except KeyError:
            self.log(f"Missing configuration option {setting}", OUTPUT_ERROR)

    def update_player(self, bw, **kwargs):
        self.players_info[bw].update(**kwargs)

    def reset_players(self):
        self.update_player("B")
        self.update_player("W")
        for v in self.players_info.values():
            v.periods_used = 0

    @property
    def last_player_info(self) -> Player:
        return self.players_info[self.game.current_node.player]

    @property
    def next_player_info(self) -> Player:
        return self.players_info[self.game.current_node.next_player]
Beispiel #39
0
class FindBWidget(BoxLayout):
    level = NumericProperty(1)
    bfound = NumericProperty(0)
    bnumber = NumericProperty(0)

    def __init__(self, **kwargs):
        super(FindBWidget, self).__init__(**kwargs)
        self.BBoxList = []
        self.store = JsonStore("findb.json")
        self.gridSize_height = 0
        self.gridSize_width = 0
        self.bnumber = 0
        self.badded = 0
        self.bfound = 0
        self.mute = True
        self.gameover = False
        self.custimize = False
        self.custimize_height = 0
        self.custimize_width = 0
        self.custimize_brate = 0.2

        self.sounds = {
            'bomb': SoundLoader.load('bomb.wav'),
            'state': SoundLoader.load('state.wav'),
            'upgrade': SoundLoader.load('upgrade.mp3')
        }

        self.start_clock = clock()
        self.config = None

    def on_bfound(self, instance, value):
        self.status_bar.label_left_bomb.text = '{}'.format(self.bnumber -
                                                           self.bfound)
        self.CheckSucceed()

    def on_bnumber(self, instance, value):
        self.status_bar.label_left_bomb.text = '{}'.format(self.bnumber -
                                                           self.bfound)

    def Restart(self):
        self.custimize, self.custimize_height, self.custimize_width, self.custimize_brate = self.get_customize_info(
        )
        self.level, self.levels_info = self.get_level_info()
        self.mute = self.get_mute_info()

        self.BBoxList = []

        if self.custimize == True:
            self.status_bar.label_level.text = 'L:C'
            self.gridSize_height = self.custimize_height
            self.gridSize_width = self.custimize_width

            if self.gridSize_height < 5:
                self.gridSize_height = 5
            if self.gridSize_width < 5:
                self.gridSize_width = 5
            if self.gridSize_height > 50:
                self.gridSize_height = 50
            if self.gridSize_width > 50:
                self.gridSize_width = 50
        else:
            self.status_bar.label_level.text = 'L:{}'.format(self.level)
            self.gridSize_width = self.level + Rows_For_First_Level
            self.gridSize_height = self.level + Rows_For_First_Level

        self.bnumber = 0
        self.badded = 0
        self.bfound = 0
        self.start_clock = clock()
        self.gameover = False
        self.play_area.clear_widgets()
        self.play_area.cols = self.gridSize_width
        self.play_area.rows = self.gridSize_height

        for i in range(0, self.gridSize_height):
            for j in range(0, self.gridSize_width):
                b = BBox(root=self)
                b.row = i
                b.col = j
                self.BBoxList.append(b)
                self.play_area.add_widget(b)

        self._calculate_bombs()

        self.status_bar.toggle_mark.disable = False
        self.status_bar.toggle_mark.state = "normal"
        self.status_bar.button_reset.image.source = 'smile.png'

    def _calculate_bombs(self):
        if self.custimize:
            self.brate = self.custimize_brate / 100.0
            if self.brate < 0.05:
                self.brate = 0.05
            if self.brate > 0.8:
                self.brate = 0.8
        elif self.level < 6:
            self.brate = 0.11
        elif self.level < 11:
            self.brate = 0.13
        elif self.level < 20:
            self.brate = 0.15
        elif self.level < 30:
            self.brate = 0.18
        else:
            self.brate = 0.2

        self.bnumber = int(self.brate * self.gridSize_width *
                           self.gridSize_height)

        self.badded = 0
        while True:
            if self._add_bomb():
                self.badded += 1

            if self.badded >= self.bnumber:
                break

    def _add_bomb(self):
        if len(self.BBoxList) <= 0:
            return

        i = Random().randint(0, len(self.BBoxList) - 1)

        if self.BBoxList[i].isBomb:
            return False
        else:
            self.BBoxList[i].isBomb = True
            #set bomb number of the around boxes
            row = self.BBoxList[i].row
            col = self.BBoxList[i].col

            self._add_bomb_number(row - 1, col - 1)
            self._add_bomb_number(row - 1, col)
            self._add_bomb_number(row - 1, col + 1)
            self._add_bomb_number(row, col - 1)
            self._add_bomb_number(row, col + 1)
            self._add_bomb_number(row + 1, col - 1)
            self._add_bomb_number(row + 1, col)
            self._add_bomb_number(row + 1, col + 1)

        return True

    def _add_bomb_number(self, row, col):
        if row < 0 or row >= self.gridSize_width or col < 0 or col >= self.gridSize_height:
            return

        index = row * self.gridSize_width + col
        if index < 0 or index >= len(self.BBoxList):
            return

        self.BBoxList[index].BNumber += 1

    def Clear(self, row, col):
        if row < 0 or row >= self.gridSize_width or col < 0 or col >= self.gridSize_height:
            return

        index = row * self.gridSize_width + col
        if index < 0 or index >= len(self.BBoxList):
            return

        self.BBoxList[index].MarkNumberOrEmpty()

    def ShowAll(self):
        self.status_bar.toggle_mark.state = 'normal'
        for i in range(0, len(self.BBoxList)):
            if self.BBoxList[i].isBomb:
                self.BBoxList[i].bbutton.MarkB()
            else:
                self.BBoxList[i].Clear()

    def CheckSucceed(self):
        if self.bfound > 0 and self.bfound == self.bnumber:
            for i in range(0, len(self.BBoxList)):
                if self.BBoxList[i].state == 0:
                    return False

            #upgrade level
            if self.mute == False:
                self.sounds['upgrade'].play()

            if self.custimize == False:
                duration = round((clock() - self.start_clock), 2)

                if self.levels_info.has_key(
                        self.level) and self.levels_info[self.level] > 0:
                    if self.levels_info[self.level] > duration:
                        self.levels_info[self.level] = duration
                else:
                    self.levels_info[self.level] = duration

                if self.level < Max_Level:
                    self.level += 1

                self.store_user_data(self.level, self.levels_info)

            self.Restart()

            return True
        else:
            return False

    def get_level_info(self):
        if self.store.exists("UserData") == False:
            self.store.put("UserData", CurrentLevel=1, Levels={})

        return self.store.get("UserData")["CurrentLevel"], self.store.get(
            "UserData")["Levels"]

    def get_mute_info(self):
        return self.config.get('Sounds', 'Mute') == '1'

    def get_customize_info(self):
        return self.config.get(
            'Customization', 'Enable') == '1', self.config.getint(
                'Customization', 'C_Height'), self.config.getint(
                    'Customization',
                    'C_Width'), self.config.getint('Customization', 'Rate')

    def store_user_data(self, currentLevel, levels):
        self.store.put("UserData", CurrentLevel=currentLevel, Levels=levels)

    def GameOver(self):
        self.status_bar.toggle_mark.disable = True
        self.status_bar.button_reset.image.source = 'gameover.png'
        self.gameover = True
Beispiel #40
0
 def on_stop(self):
     local_store = JsonStore('library/local_user.json')
     local_store.put('local_user', local_ID=local_user.local_ID)
Beispiel #41
0
class KognitivoApp(App):
    use_kivy_settings = False

    user_data_dir = settings.DATABASE_PATH

    def open_settings(self, *largs):
        if not self.settings_cls:
            from settings_widget import KognitivoSettings

            self.settings_cls = KognitivoSettings
        super(KognitivoApp, self).open_settings(*largs)

    def on_stop(self):
        if platform == 'linux':
            self.profile.disable()
            self.profile.dump_stats('kognitivo.profile')
        self.profiler.print_all()
        if self.billing:
            self.billing.unbind()

    @property
    def tracker(self):
        if not self._tracker:
            Logger.info("Tracker: initialization")
            from tracking import Tracker

            self._tracker = Tracker()
        return self._tracker

    def _initialize_storage(self):
        Logger.info("Storage: initialization")

        from kivy.storage.jsonstore import JsonStore

        self._storage = JsonStore("storage-%s.json" % self.name)
        import settings

        for key, config in settings.DEFAULT_STORAGE_CONFIG.items():
            if key not in self._storage:
                self._storage.put(key, **config)

        records = self._storage["task_records"]
        for key in settings.TASKS:
            if key not in records:
                records[key] = 0
        self._storage.put("task_records", **records)

        starts_count = self._storage['starts']['count']

        self.tracker.send_event('general', 'start', value=starts_count + 1)
        self._storage['starts'] = {"count": starts_count + 1}
        Logger.info("Storage: started %s times" %
                    self._storage['starts']['count'])

    @property
    def storage(self):
        if not self._storage:
            self._initialize_storage()
        return self._storage

    def _initialize_gplay_services(self):
        from gplay import GoogleClient
        import settings
        self._google_client = GoogleClient()

        if not settings.PROFILE:
            auto_login = self.config.get('preferences', 'google_auto_login')
            if auto_login == "1":
                self._google_client.connect()

    @property
    def google_client(self):
        if not self._google_client:
            Logger.info("Google: initialization")
            self._initialize_gplay_services()
        return self._google_client

    def initialize_cprofile(self):
        if platform == 'linux':
            import cProfile

            self.profile = cProfile.Profile()
            self.profile.enable()

    def __init__(self, name=None, **kwargs):
        from utils import NaiveProfiler

        self.profiler = NaiveProfiler()
        self.initialize_cprofile()
        self.profiler.fix_from("---app-init")

        # lazy attributes
        self._tracker = None
        self._sounds = None
        self.billing = None
        self._storage = None
        self.lang = None
        self.manager = None
        self._google_client = None
        self.profiler.fix_from("super init")
        super(KognitivoApp, self).__init__(**kwargs)
        self.profiler.fix_to("super init")

        self.db_path = None
        self.profiler.fix_from("import-configure")
        from configure import configure

        self.profiler.fix_to("import-configure")

        self.profiler.fix_from("configure")
        configure()
        self.profiler.fix_to("configure")

        from settings import DEVELOPMENT_VERSION

        if name is None:
            KognitivoApp.name = "kognitivo-dev" if DEVELOPMENT_VERSION else "kognitivo"
        else:
            KognitivoApp.name = name
        self.service = None

        self.profiler.fix_to("---app-init")

    def build_service_params(self):
        params = {
            "enable_notifications":
            self.config.get('preferences', 'enable_notifications'),
            "morning_notification_time":
            self.config.get('preferences', 'morning_notification_time'),
            "lunch_notification_time":
            self.config.get('preferences', 'lunch_notification_time'),
            "evening_notification_time":
            self.config.get('preferences', 'evening_notification_time'),
            "language":
            self.config.get('preferences', 'language'),
        }
        return params

    def schedule_notifications(self, force=False):
        if platform == 'android':
            from notifications_scheduler import Scheduler

            scheduler = Scheduler([
                self.config.get('preferences', 'morning_notification_time'),
                self.config.get('preferences', 'lunch_notification_time'),
                self.config.get('preferences', 'evening_notification_time')
            ])
            enable_notifications = int(
                self.config.get('preferences', 'enable_notifications'))
            if enable_notifications == 1:
                Logger.debug("Notifications: Creating schedules...")
                if force:
                    scheduler.clean_schedules()
                scheduler.create_schedule()
                Logger.debug("Notifications: Finished creating schedules")
            elif enable_notifications == 0:
                if force:
                    scheduler.clean_schedules()
            return
        else:
            Logger.info("Notifications: no notifications on %s" % platform)

    def set_language(self):
        if platform == 'android':
            if self.config.get('preferences', 'language') == 'system':
                Logger.info("Locale: Setting locale to system preference...")
                from jnius import autoclass

                Locale = autoclass('java.util.Locale')

                try:
                    system_language = Locale.getDefault().getLanguage()
                except Exception:
                    system_language = 'en'

                Logger.info("Locale: System locale is %s" % system_language)
                from settings import LANGUAGES

                if system_language in LANGUAGES:
                    self.lang = system_language
                    self.config.set('preferences', 'language', system_language)
                else:
                    Logger.info(
                        "Locale: System locale is unknown. Falling back to english..."
                    )
                    self.lang = 'en'
                    self.config.set('preferences', 'language', 'en')
                self.config.write()
        self.lang = self.config.get('preferences', 'language')
        from utils import _

        _.switch_lang(self.lang)

    def _initialize_sounds(self):
        Logger.info('App: initialize sounds')
        if settings.SOUND_ENABLED and int(
                self.config.get('preferences', 'sound')) == 1:
            self._sounds = {}
            from settings import SOUNDS
            from kivy.core.audio import SoundLoader

            for name, path in SOUNDS.items():
                self._sounds[name] = SoundLoader.load(path)
        else:
            from collections import defaultdict
            from kivy.core.audio import Sound

            self._sounds = defaultdict(Sound)

    def initialize_billing(self, callback=None, *args):
        if not self.billing:
            Logger.info("Billing: initialization")
            self.profiler.fix_from('billing')
            from billing import BillingService

            self.billing = BillingService()
            self.billing.bind(callback)
            self.profiler.fix_to('billing')
        else:
            if callback:
                callback()

    @property
    def sounds(self):
        if not self._sounds:
            self._initialize_sounds()
        return self._sounds

    def build(self):
        self.profiler.fix_from('---build')
        self.profiler.fix_from('set_language')
        self.set_language()
        self.profiler.fix_to('set_language')

        self.profiler.fix_from('schedule_notifications')
        self.schedule_notifications()
        self.profiler.fix_to('schedule_notifications')

        self.profiler.fix_from('import-root-widget')
        from root_manager import RootManager

        self.profiler.fix_to('import-root-widget')

        self.profiler.fix_from('build-root-widget')
        import settings

        root = RootManager()
        from managers.database import database_manager
        if database_manager.total_count() > 1:
            from screens.activity.activity import ActivityScreen
            start_screen = ActivityScreen()
            menu_state = 'open'
        else:
            from screens.tutorial import TutorialScreen
            start_screen = TutorialScreen()
            menu_state = 'closed'

        root.add_widget(start_screen)
        from screens.menu import KognitivoNavigator
        navigator = KognitivoNavigator()
        navigator.add_widget(root)
        navigator.state = menu_state

        from kivy.core.window import Window
        Window.clearcolor = (1, 1, 1, 1)
        if settings.DEVELOPMENT_VERSION and settings.INSPECT and platform == 'linux':
            from kivy.modules import inspector
            inspector.create_inspector(Window, root)
        self.profiler.fix_to('build-root-widget')
        self.manager = root

        self.bind(on_start=self.post_build_init)

        self.profiler.fix_to('---build')
        return navigator

    def post_build_init(self, *_):
        self.profiler.fix_from('post-build')
        from managers.facebook import facebook_manager
        facebook_manager.initialize()
        from kivy.core.window import Window

        win = Window
        win.bind(on_keyboard=self.key_handler)
        self.root.attach_toggle(win)
        self.profiler.fix_to('post-build')

    # noinspection PyUnusedLocal
    def key_handler(self, window, keycode1, *_):
        if keycode1 in [27, 1001]:
            if not self.close_settings():
                self.manager.go_back()
            return True
        return False

    def build_settings(self, settings):
        with open("settings.json", "r") as settings_json:
            from utils import _

            settings.add_json_panel(_('SETTINGS'),
                                    self.config,
                                    data=settings_json.read())

    def build_config(self, config):
        from settings import KIVY_DEFAULT_CONFIG

        for section, conf in KIVY_DEFAULT_CONFIG.items():
            config.setdefaults(section, conf)

    def on_pause(self):
        from managers.facebook import facebook_manager
        facebook_manager.activate()
        return True

    def on_resume(self):
        from managers.facebook import facebook_manager
        facebook_manager.deactivate()

    def on_config_change(self, config, section, key, value):
        self.schedule_notifications(force=True)
        if section == 'preferences':
            if key == 'language':
                Logger.info("Settings: change locale to %s" % value)
                self.lang = value

            if key == 'sound':
                self._initialize_sounds()

            if key == 'enable_notifications':
                self.tracker.send_event(
                    'general', 'notifications',
                    'disabled' if value == "0" else 'enabled')
Beispiel #42
0
class _2048Controller:
	def __init__(self):
		self.width = 4
		self.height = 4
		self.store = JsonStore('data.json')
		self.best_score = 0
		if self.store.exists('score'):
			self.best_score = self.store.get('score')['best_score']
		self.initGame()

	def initGame(self):
		self.score = 0
		self.undo_left = 2
		self.undo_game_array = []
		self.game_array = self.generateGameArray()
		#self.game_array = [[0, 0, 8, 16], [32, 64, 128, 256], [512, 1024, 2048, 4096], [8192, 16384, 32768, 65536]]
		self.end_game = False
		self.new_number_array = []  # list of new number is generated
		self.undo_game_array = []  # ####
		for i in range(2):
			self.generateNumber()  # generate 2 new numbers

	def checkExists(self, x, y):
		return self.game_array[y][x] != 0

	def generateGameArray(self):
		game_board = []
		for y in range(self.height):
			rows = []
			for x in range(self.width):
				rows.append(0)
			game_board.append(rows)
		return game_board

	def generateNumber(self):
		while True:  # loop until the position is valid
			x = random.randint(0, self.width - 1)
			y = random.randint(0, self.height - 1)
			if not self.checkExists(x, y):
				number = 2
				if random.randint(1, 100) > 80:
					number = 4
				self.game_array[y][x] = number
				break
		self.new_number_array.append((x, y))

	def slideUp(self, game_board=None):
		if not game_board:
			game_board = self.game_array
		moved = False
		score = 0
		animation_way = []
		for x in range(self.width):
			notCombineList = []
			for y in range(self.height):
				if game_board[y][x] == 0:
					continue
				for stop_y in range(y - 1, -1, -1):
					if game_board[stop_y][x] != 0:
						if game_board[stop_y][x] == game_board[y][x] and stop_y not in notCombineList:
								game_board[stop_y][x] *= 2
								game_board[y][x] = 0
								moved = True
								score += game_board[stop_y][x]
								notCombineList.append(stop_y)
								animation_way.append([(x, y), (x, stop_y)])
						else:
							game_board[stop_y + 1][x], game_board[y][x] = game_board[y][x], game_board[stop_y + 1][x]
							if y != stop_y + 1:
								animation_way.append([(x, y), (x, stop_y + 1)])
								moved = True
						break
					if stop_y == 0 and game_board[0][x] == 0 and game_board[y][x] != game_board[0][x]:
						game_board[0][x], game_board[y][x] = game_board[y][x], game_board[0][x]
						moved = True
						animation_way.append([(x, y), (x, stop_y)])
		return [moved, score, animation_way]

	def slideDown(self, game_board=None):
		if not game_board:
			game_board = self.game_array
		moved = False
		score = 0
		animation_way = []
		for x in range(self.width):
			notCombineList = []
			for y in range(self.width - 1, -1, -1):
				if game_board[y][x] == 0:
					continue
				for stop_y in range(y + 1, self.height):
					if game_board[stop_y][x] != 0:
						if game_board[stop_y][x] == game_board[y][x] and stop_y not in notCombineList:
								game_board[stop_y][x] *= 2
								game_board[y][x] = 0
								moved = True
								score += game_board[stop_y][x]
								notCombineList.append(stop_y)
								animation_way.append([(x, y), (x, stop_y)])
						else:
							game_board[stop_y - 1][x], game_board[y][x] = game_board[y][x], game_board[stop_y - 1][x]
							if y != stop_y - 1:
								animation_way.append([(x, y), (x, stop_y - 1)])
								moved = True
						break
					if stop_y == (self.height - 1) and game_board[self.height - 1][x] == 0 and \
							game_board[y][x] != game_board[self.height - 1][x]:
						game_board[self.height - 1][x], game_board[y][x] = game_board[y][x], game_board[self.height - 1][x]
						moved = True
						animation_way.append([(x, y), (x, stop_y)])
		return [moved, score, animation_way]

	def slideLeft(self, game_board=None):
		if not game_board:
			game_board = self.game_array
		moved = False
		score = 0
		animation_way = []
		for y in range(self.height):
			notCombineList = []
			for x in range(1, self.width):
				if game_board[y][x] == 0:
					continue
				for stop_x in range(x - 1, -1, -1):
					if game_board[y][stop_x] != 0:
						if game_board[y][stop_x] == game_board[y][x] and stop_x not in notCombineList:
							game_board[y][stop_x] *= 2
							game_board[y][x] = 0
							moved = True
							score += game_board[y][stop_x]
							notCombineList.append(stop_x)
							animation_way.append([(x, y), (stop_x, y)])
						else:
							game_board[y][stop_x + 1], game_board[y][x] = game_board[y][x], game_board[y][stop_x + 1]
							if x != stop_x + 1:
								animation_way.append([(x, y), (stop_x + 1, y)])
								moved = True
						break
					if stop_x == 0 and game_board[y][0] == 0 and game_board[y][x] != game_board[y][0]:
						game_board[y][0], game_board[y][x] = game_board[y][x], game_board[y][0]
						moved = True
						animation_way.append([(x, y), (stop_x, y)])
		return [moved, score, animation_way]

	def slideRight(self, game_board=None):
		if not game_board:
			game_board = self.game_array
		moved = False
		score = 0
		animation_way = []
		for y in range(self.height):
			notCombineList = []
			for x in range(self.width - 2, -1, -1):
				if game_board[y][x] == 0:
					continue
				for stop_x in range(x + 1, self.width):
					if game_board[y][stop_x] != 0:
						if game_board[y][stop_x] == game_board[y][x] and stop_x not in notCombineList:
							game_board[y][stop_x] *= 2
							game_board[y][x] = 0
							moved = True
							score += game_board[y][stop_x]
							notCombineList.append(stop_x)
							animation_way.append([(x, y), (stop_x, y)])
						else:
							game_board[y][stop_x - 1], game_board[y][x] = game_board[y][x], game_board[y][stop_x - 1]
							if x != stop_x - 1:
								animation_way.append([(x, y), (stop_x - 1, y)])
								moved = True
						break
					if stop_x == (self.width - 1) and game_board[y][self.width - 1] == 0 and\
							game_board[y][x] != game_board[y][self.width - 1]:
						game_board[y][self.width - 1], game_board[y][x] = game_board[y][x], game_board[y][self.width - 1]
						moved = True
						animation_way.append([(x, y), (stop_x, y)])
		return [moved, score, animation_way]

	def checkForWin(self):
		for y in range(len(self.game_array)):
			for x in range(len(self.game_array[0])):
				if self.game_array[y][x] == 2048:
					return True
				else:
					return False

	def checkForBestScore(self):
		if self.score > self.best_score:
			self.best_score = self.score

	def saveData(self):
		self.store.put('score', best_score=self.best_score)

	def up(self):
		tmp_game_array = copy.deepcopy(self.game_array)
		tmp_score = self.score
		moved, score, animation_way = self.slideUp()
		self.score += score
		self.checkForBestScore()
		if not self.existsMove() and self.undo_left == 0:
			self.end_game = True
		elif moved:
			self.undo_game_array.append([tmp_game_array, tmp_score])
			self.generateNumber()
		return animation_way

	def down(self):
		tmp_game_array = copy.deepcopy(self.game_array)
		tmp_score = self.score
		moved, score, animation_way = self.slideDown()
		self.score += score
		self.checkForBestScore()
		if not self.existsMove() and self.undo_left == 0:
			self.end_game = True
		elif moved:
			self.undo_game_array.append([tmp_game_array, tmp_score])
			self.generateNumber()
		return animation_way

	def left(self):
		tmp_game_array = copy.deepcopy(self.game_array)
		tmp_score = self.score
		moved, score, animation_way = self.slideLeft()
		self.score += score
		self.checkForBestScore()
		if not self.existsMove() and self.undo_left == 0:
			self.end_game = True
		elif moved:
			self.undo_game_array.append([tmp_game_array, tmp_score])
			self.generateNumber()
		return animation_way

	def right(self):
		tmp_game_array = copy.deepcopy(self.game_array)
		tmp_score = self.score
		moved, score, animation_way = self.slideRight()
		self.score += score
		self.checkForBestScore()
		if not self.existsMove() and self.undo_left == 0:
			self.end_game = True
		elif moved:
			self.undo_game_array.append([tmp_game_array, tmp_score])
			self.generateNumber()
		return animation_way

	def existsMove(self):
		exists = False
		#if self.slideUp(game_array_clone)[0] or self.slideDown(game_array_clone)[0] or \
		#	self.slideLeft(game_array_clone)[0] or self.slideRight(game_array_clone)[0]:
		#	exists = True
		for test in (self.slideLeft, self.slideRight, self.slideUp, self.slideDown):
			game_array_clone = copy.deepcopy(self.game_array)  # clone the game array to check
			if test(game_array_clone)[0]:
				exists = True
		return exists

	def undo(self):
		if self.undo_left == 0 or len(self.undo_game_array) == 0:  # if start game or out of undo left, not do undo
			return
		self.undo_left -= 1
		temp_array, temp_score = self.undo_game_array.pop()  # pop the undo data (array and score)
		for y in range(len(temp_array)):         # dont do this : self.game_array = temp.array
			for x in range(len(temp_array[0])):  # because it reference to new list, not a current list, it wont work
				self.game_array[y][x] = temp_array[y][x]
		self.score = temp_score
Beispiel #43
0
class RobRehabGUI( Widget ):
  connection = None
  currentServerAddress = None

  UPDATE_INTERVAL = 0.02

  setpointsUpdated = True

  isCalibrating = False
  isSampling = False
  isOperating = False
  samplingEvent = None
  operationEvent = None

  JOINT = 0
  AXIS = 1
  deviceIDs = ( [], [] )
  currentDeviceIndexes = [ None for i in range( len(deviceIDs) ) ]
  NULL_ID = '<Select>'

  axisMeasures = [ 0.0 for var in range( DOF_VARS_NUMBER ) ]
  setpoints = [ 0.0 for var in range( DOF_VARS_NUMBER ) ]
  jointMeasures = [ 0.0 for var in range( DOF_VARS_NUMBER ) ]

  class DataPlot:
    def __init__( self, handle, values, source, offset ):
      self.handle = handle
      self.values = values
      self.source = source
      self.offset = offset
  dataPlots = []
  INITIAL_VALUES = [ 0.0 for value in range( 101 ) ]

  def __init__( self, **kwargs ):
    super( RobRehabGUI, self ).__init__( **kwargs )

    self.configStorage = JsonStore( 'config.json' )
    if self.configStorage.exists( 'server' ): self.ids[ 'address_input' ].text = self.configStorage.get( 'server' )[ 'address' ]
    if self.configStorage.exists( 'user' ): self.ids[ 'user_name_input' ].text = self.configStorage.get( 'user' )[ 'name' ]

    self.deviceSelectors = ( self.ids[ 'joint_selector' ], self.ids[ 'axis_selector' ] )
    self.deviceEntries = [ DropDown() for selector in self.deviceSelectors ]
    for index in range( len(self.deviceEntries) ):
      def SelectEntry( instance, name, index=index ):
        self.SetDevice( index, name )
      self.deviceEntries[ index ].bind( on_select=SelectEntry )
      self.deviceSelectors[ index ].bind( on_release=self.deviceEntries[ index ].open )

    dataGraph = self.ids[ 'data_graph' ]

    measure_range = self.ids[ 'measure_slider' ].range
    GRAPH_PROPERTIES = { 'xlabel':'Last Samples', 'x_ticks_minor':5, 'x_ticks_major':25, 'y_ticks_major':0.25, 'y_grid_label':True, 'x_grid_label':True,
                         'padding':5, 'x_grid':True, 'y_grid':True, 'xmin':0, 'xmax':len(self.INITIAL_VALUES) - 1, 'ymin':measure_range[ 0 ], 'ymax':measure_range[ 1 ],
                         'background_color':[ 1, 1, 1, 1 ], 'tick_color':[ 0, 0, 0, 1 ], 'border_color':[ 0, 0, 0, 1 ], 'label_options':{ 'color': [ 0, 0, 0, 1 ], 'bold':True } }

    axisPositionGraph = Graph( ylabel='Position', **GRAPH_PROPERTIES )
    axisPositionPlot = SmoothLinePlot( color=[ 0, 0, 1, 1 ] )
    axisPositionGraph.add_plot( axisPositionPlot )
    self.dataPlots.append( RobRehabGUI.DataPlot( axisPositionPlot, self.INITIAL_VALUES[:], self.axisMeasures, DOF_POSITION ) )
    axisVelocityPlot = SmoothLinePlot( color=[ 0, 1, 0, 1 ] )
    axisPositionGraph.add_plot( axisVelocityPlot )
    self.dataPlots.append( RobRehabGUI.DataPlot( axisVelocityPlot, self.INITIAL_VALUES[:], self.axisMeasures, DOF_VELOCITY ) )
    refPositionPlot = SmoothLinePlot( color=[ 0, 0, 0.5, 1 ] )
    axisPositionGraph.add_plot( refPositionPlot )
    self.dataPlots.append( RobRehabGUI.DataPlot( refPositionPlot, self.INITIAL_VALUES[:], self.setpoints, DOF_POSITION ) )
    refVelocityPlot = SmoothLinePlot( color=[ 0, 0.5, 0, 1 ] )
    axisPositionGraph.add_plot( refVelocityPlot )
    self.dataPlots.append( RobRehabGUI.DataPlot( refVelocityPlot, self.INITIAL_VALUES[:], self.setpoints, DOF_VELOCITY ) )
    axisAccelerationPlot = SmoothLinePlot( color=[ 1, 0, 0, 1 ] )
    axisPositionGraph.add_plot( axisAccelerationPlot )
    self.dataPlots.append( RobRehabGUI.DataPlot( axisAccelerationPlot, self.INITIAL_VALUES[:], self.axisMeasures, DOF_ACCELERATION ) )
    dataGraph.add_widget( axisPositionGraph )

    dataGraph.add_widget( Label( size_hint_y=0.05 ) )

    axisForceGraph = Graph( ylabel='Torque', **GRAPH_PROPERTIES )
    axisForcePlot = SmoothLinePlot( color=[ 1, 0, 0, 1 ] )
    axisForceGraph.add_plot( axisForcePlot )
    self.dataPlots.append( RobRehabGUI.DataPlot( axisForcePlot, self.INITIAL_VALUES[:], self.axisMeasures, DOF_FORCE ) )
    dataGraph.add_widget( axisForceGraph )

    Clock.schedule_interval( self.NetworkUpdate, self.UPDATE_INTERVAL / 2 )
    Clock.schedule_interval( self.GraphUpdate, self.UPDATE_INTERVAL * 2 )
    Clock.schedule_interval( self.SliderUpdate, self.UPDATE_INTERVAL )

  def ConnectClient( self, serverAddress ):
    self.connection = None
    self.robotID = ''
    self.deviceIDs = ( [], [] )
    serverType, serverHost = serverAddress.split( '://' )
    print( 'acquired %s server host: %s' % ( serverType, serverHost ) )
    if serverType == 'ip': self.connection = ipclient.Connection()
    if self.connection is not None:
      self.configStorage.put( 'server', address=serverAddress )
      self.connection.Connect( serverHost )
      self.robotID, self.deviceIDs = self.connection.RefreshInfo()

    self.ids[ 'robot_id_display' ].text = self.robotID

    def UpdateSelectorEntries( selector, entriesList, entryNames ):
      entriesList.clear_widgets()
      for name in entryNames:
        entryButton = Button( text=name, size_hint_y=None )
        entryButton.height = entryButton.font_size * 2
        entryButton.bind( on_release=lambda button: entriesList.select( button.text ) )
        entriesList.add_widget( entryButton )

    for deviceType in range( len(self.deviceIDs) ):
      UpdateSelectorEntries( self.deviceSelectors[ deviceType ], self.deviceEntries[ deviceType ], self.deviceIDs[ deviceType ] )
      self.SetDevice( deviceType, self.deviceIDs[ deviceType ][ 0 ] if len(self.deviceIDs[ deviceType ]) > 0 else self.NULL_ID )

  def GraphUpdate( self, dt ):
    for plot in self.dataPlots:
      if len(plot.values) >= len(self.INITIAL_VALUES):
        plot.handle.points = [ ( sample, plot.values[ sample ] ) for sample in range( len(self.INITIAL_VALUES) ) ]
        plot.values = []
      plot.values.append( plot.source[ plot.offset ] )

  def SliderUpdate( self, dt ):
    self.ids[ 'measure_slider' ].value = self.axisMeasures[ DOF_POSITION ] #* 180 / math.pi

  def NetworkUpdate( self, dt ):
    currentAxisIndex = self.currentDeviceIndexes[ self.AXIS ]
    currentJointIndex = self.currentDeviceIndexes[ self.JOINT ]
    if self.connection is not None and currentAxisIndex is not None:
      if self.setpointsUpdated:
        self.connection.SendAxisSetpoints( currentAxisIndex, self.setpoints )
        self.setpointsUpdated = False
      self.connection.ReceiveAxisMeasures( currentAxisIndex, self.axisMeasures )
      #print( 'NetworkUpdate: received axis measures: ' + str( self.axisMeasures ) )
      #self.connection.ReceiveJointMeasures( currentJointIndex, self.jointMeasures )

  def SetUserName( self, name ):
    if self.connection is not None: self.connection.SetUser( name )
    self.configStorage.put( 'user', name=name )

  def SetDevice( self, type, name ):
    self.deviceSelectors[ type ].text = name
    deviceIDs = self.deviceIDs[ type ]
    self.currentDeviceIndexes[ type ] = deviceIDs.index( name ) if ( name in deviceIDs ) else None

  def SetSetpoints( self ):
    if not self.isSampling:
      self.setpoints[ DOF_POSITION ] = self.ids[ 'setpoint_slider' ].value #* math.pi / 180
      self.setpoints[ DOF_STIFFNESS ] = self.ids[ 'stiffness_slider' ].value
      self.setpoints[ DOF_DAMPING ] = self.ids[ 'damping_slider' ].value
    self.setpointsUpdated = True

  def _SendCommand( self, commandKey ):
    self.connection.SendCommand( commandKey )

  def SetEnable( self, enabled ):
    offsetToggle = self.ids[ 'offset_button' ]
    if enabled:
      self._SendCommand( ENABLE )
      offsetToggle.state = 'down'
    else:
      self._SendCommand( DISABLE )
      offsetToggle.state = 'normal'

  def SetOffset( self, enabled ):
    if enabled: self._SendCommand( OFFSET )
    else:
      self._SendCommand( OPERATE if self.isOperating else PASSIVATE )
      self.ids[ 'setpoint_slider' ].value = 0
      self.SetSetpoints()

  def SetCalibration( self, enabled ):
    self.isCalibrating = enabled
    calibrationLED = self.ids[ 'indication_led' ]

    def TurnLedOn( *args ):
      calibrationLED.color = [ 0, 1, 0, 1 ]
      Clock.schedule_once( TurnLedOff, 5.0 )
    def TurnLedOff( *args ):
      calibrationLED.color = [ 1, 0, 0, 1 ]
      if self.isCalibrating: Clock.schedule_once( TurnLedOn, 3.0 )

    if enabled:
      self._SendCommand( CALIBRATE )
      TurnLedOn()
    else:
      self._SendCommand( OPERATE if self.isOperating else PASSIVATE )
      TurnLedOff()

  def SetOptimization( self, enabled ):
    PHASE_CYCLES_NUMBER = 5
    PHASE_CYCLE_INTERVAL = 8.0
    SETPOINT_AMPLITUDE = math.pi / 4
    #SETPOINT_AMPLITUDE_ANGLE = SETPOINT_AMPLITUDE * 180 / math.pi
    PHASE_INTERVAL = PHASE_CYCLES_NUMBER * PHASE_CYCLE_INTERVAL
    PHASES_STIFFNESS_LIST = [     0,    30,    60,   60,   30,    0,    0,   10 ]
    PHASES_DIRECTION_LIST = [     1,     1,     1,    1,    1,    1,   -1,   -1 ]
    PHASES_ACTIVE_LIST =    [ False, False, False, True, True, True, True, True ]
    TOTAL_SAMPLING_INTERVAL = len(PHASES_STIFFNESS_LIST) * PHASE_INTERVAL

    self.isSampling = enabled
    self.samplingTime = 0.0

    setpointSlider = self.ids[ 'setpoint_slider' ]
    stiffnessSlider = self.ids[ 'stiffness_slider' ]
    dampingSlider = self.ids[ 'damping_slider' ]
    activeLED = self.ids[ 'indication_led' ]
    def UpdateSetpoint( delta ):
      phaseIndex = int( self.samplingTime / PHASE_INTERVAL )
      if phaseIndex >= len(PHASES_STIFFNESS_LIST):
        self.ids[ 'sampling_button' ].state = 'normal'
        return False
      self.samplingTime += delta
      setpointDirection = PHASES_DIRECTION_LIST[ phaseIndex ]
      activeLED.color = [ 0, 1, 0, 1 ] if PHASES_ACTIVE_LIST[ phaseIndex ] else [ 1, 0, 0, 1 ]
      setpoint = math.sin( 2 * math.pi * self.samplingTime / PHASE_CYCLE_INTERVAL )
      setpointSlider.value = setpoint * SETPOINT_AMPLITUDE #SETPOINT_AMPLITUDE_ANGLE #- SETPOINT_AMPLITUDE_ANGLE
      self.setpoints[ DOF_POSITION ] = setpoint * SETPOINT_AMPLITUDE * setpointDirection - SETPOINT_AMPLITUDE
      targetStiffness = PHASES_STIFFNESS_LIST[ phaseIndex ]
      stiffnessSlider.value = stiffnessSlider.value * 0.9 + targetStiffness * 0.1
      self.setpoints[ DOF_STIFFNESS ] = stiffnessSlider.value
      dampingSlider.value = 0.0

    if enabled:
      self._SendCommand( PREPROCESS )
      self.samplingEvent = Clock.schedule_interval( UpdateSetpoint, self.UPDATE_INTERVAL * 2 )
    else:
      self.samplingTime = TOTAL_SAMPLING_INTERVAL
      setpointSlider.value = 0.0
      stiffnessSlider.value = 0.0
      dampingSlider.value = 0.0
      activeLED.color = [ 1, 0, 0, 1 ]
      self._SendCommand( OPERATE if self.isOperating else PASSIVATE )
      self.samplingEvent.cancel()

  def SetOperation( self, enabled ):
    PHASE_CYCLE_INTERVAL = 8.0
    SETPOINT_AMPLITUDE = math.pi / 4
    #SETPOINT_AMPLITUDE_ANGLE = SETPOINT_AMPLITUDE * 180 / math.pi

    self.isOperating = enabled
    self.operationTime = 0.0

    import numpy
    from scipy import signal
    self.trajectory = numpy.loadtxt( 'positionknee.txt' )
    self.trajectory = numpy.reshape( self.trajectory, numpy.size( self.trajectory ) )
    self.trajectory = signal.resample( self.trajectory, int(len(self.trajectory) / 2) )
    print( self.trajectory )
    self.curveStep = 0
    self.setpoints[ DOF_STIFFNESS ] = 0
    #self.hasStarted = False

    setpointSlider = self.ids[ 'setpoint_slider' ]
    stiffnessSlider = self.ids[ 'stiffness_slider' ]
    dampingSlider = self.ids[ 'damping_slider' ]
    activeLED = self.ids[ 'indication_led' ]
    def UpdateSetpoint( delta ):
      #cyclesCount = int( self.operationTime / PHASE_CYCLE_INTERVAL )
      #self.operationTime += delta
      #setpoint = math.sin( 2 * math.pi * self.operationTime / PHASE_CYCLE_INTERVAL )
      #if self.hasStarted:
      setpoint = - float( self.trajectory[ self.curveStep % len(self.trajectory) ] )
      self.curveStep += 1
      setpointSlider.value = setpoint * SETPOINT_AMPLITUDE #SETPOINT_AMPLITUDE_ANGLE #- SETPOINT_AMPLITUDE_ANGLE
      #elif self.setpoints[ DOF_STIFFNESS ] > 0:
      #  if( abs( self.setpoints[ DOF_POSITION ] - self.axisMeasures[ DOF_POSITION ] ) ) < 0.0001:
      #    self.hasStarted = True
      #stiffnessSlider.value = self.axisMeasures[ DOF_STIFFNESS ]
      #if cyclesCount < 20: self.setpoints[ DOF_STIFFNESS ] = 60
      #else: self.setpoints[ DOF_STIFFNESS ] = 0
      #self.setpoints[ DOF_STIFFNESS ] = 60

    if enabled:
      self._SendCommand( OPERATE )
      activeLED.color = [ 0, 1, 0, 1 ]
      self.operationEvent = Clock.schedule_interval( UpdateSetpoint, self.UPDATE_INTERVAL * 2 )
    else:
      setpointSlider.value = 0.0
      stiffnessSlider.value = 0.0
      dampingSlider.value = 0.0
      activeLED.color = [ 1, 0, 0, 1 ]
      self._SendCommand( PASSIVATE )
      self.operationEvent.cancel()
Beispiel #44
0
    def __init__(self,**kwargs):
        super(MainScreen,self).__init__(**kwargs)
        js=JsonStore(filename="UmutRss.json")
        js.put("current_rss",title=u"Haber Türk",url={"gundem": "http://www.haberturk.com/rss/manset.xml",
                                                "siyaset": "http://www.haberturk.com/rss/siyaset.xml",
                                                "dunya": "http://www.haberturk.com/rss/dunya.xml",
                                                "yasam": "http://www.haberturk.com/rss/yasam.xml",
                                                "sanat": "http://www.haberturk.com/rss/kultur-sanat.xml",
                                                "ekonomi": "http://www.haberturk.com/rss/ekonomi.xml",
                                                "spor": "http://www.haberturk.com/rss/spor.xml"})
        js.put("Sabah",title="Sabah",url={"gundem": "http://www.sabah.com.tr/rss/gundem.xml",
                     "saglik": "http://www.sabah.com.tr/rss/saglik.xml",
                     "dunya": "http://www.sabah.com.tr/rss/dunya.xml",
                     "sanat": "http://www.sabah.com.tr/rss/kultur_sanat.xml",
                     "ekonomi": "http://www.sabah.com.tr/rss/ekonomi.xml",
                     "spor": "http://www.sabah.com.tr/rss/spor.xml",
                     "yasam": "http://www.sabah.com.tr/rss/yasam.xml",
                     "oyun": "http://www.sabah.com.tr/rss/oyun.xml",
                     "sondakika": "http://www.sabah.com.tr/rss/sondakika.xml",
                     "teknoloji": "http://www.sabah.com.tr/rss/teknoloji.xml"})
        js.put("BBC",title="BBC",url={"gundem": "http://feeds.bbci.co.uk/turkce/rss.xml"
                                      })
        js.put("Cmh",title="Cumhuriyet",url={"egitim":"http://www.cumhuriyet.com.tr/rss/18.xml",
                                             "yasam":"http://www.cumhuriyet.com.tr/rss/10.xml",
                                             "sanat":"http://www.cumhuriyet.com.tr/rss/7.xml",
                                             "dunya":"http://www.cumhuriyet.com.tr/rss/5.xml",
                                             "sondakika":"http://www.cumhuriyet.com.tr/rss/son_dakika.xml",
                                             "gundem":"http://www.cumhuriyet.com.tr/rss/1.xml"

        })
        js.put("AHaber",title="A Haber",url={"gundem": "http://www.ahaber.com.tr/rss/gundem.xml",
                                      "ekonomi": "http://www.ahaber.com.tr/rss/ekonomi.xml",
                                      "spor": "http://www.ahaber.com.tr/rss/spor.xml",
                                       "saglik": "http://www.ahaber.com.tr/rss/saglik.xml",
                                        "dunya": "http://www.ahaber.com.tr/rss/dunya.xml",
                                        "manset": "http://www.ahaber.com.tr/rss/haberler.xml",
                                        "yasam": "http://www.ahaber.com.tr/rss/yasam.xml",
                                        "anasayfa": "http://www.ahaber.com.tr/rss/anasayfa.xml",
                                        "ozelhaber": "http://www.ahaber.com.tr/rss/ozel-haberler.xml",
                                        "teknoloji": "http://www.ahaber.com.tr/rss/teknoloji.xml"
                                           })

        titles=JsonStore(filename="titles.json")
        titles.put("titles",all={"gundem":u"Gündem","egitim":u"Eğitim","dunya":u"Dünya","sanat":u"Sanat",
                                 "ekonomi":u"Ekonomi","spor":u"Spor","saglik":u"Sağlık","yasam":u"Yaşam",
                                 "oyun":u"Oyun","sondakika":u"Son Dakika","teknoloji":u"Teknoloji",
                                 "basinozeti":u"Basın Özeti","ozelhaber":u"Özel Haber","anasayfa":"Anasayfa",
                                 "turkiye":u"Türkiye","siyaset":"Siyaset","manset":u"Manşet"})
Beispiel #45
0
    def __init__(self, **kwargs):
        super(MainBox, self).__init__(**kwargs)
        data_json = JsonStore(os.path.join("data/rogue_trader_data.json"))
        for key in data_json.keys():
            self.data[key] = data_json[key]
        global data
        data = self.data
        user_dir = pathlib.Path(App.get_running_app().user_data_dir)

        # Load config
        global config
        config = JsonStore(user_dir / "config.json")
        if not config.exists("config"):
            config.put("config", **default_config)

        dos_algorithm = DoSAlgorithm(config.get("config")["dos_algorithm"])
        if dos_algorithm == DoSAlgorithm.ROGUE_TRADER:
            self.ids["dos_rt"].state = "down"
        elif dos_algorithm == DoSAlgorithm.MIXED:
            self.ids["dos_mixed"].state = "down"
        else:
            self.ids["dos_dh2"].state = "down"

        self.ids["dos_rt"].algorithm = DoSAlgorithm.ROGUE_TRADER
        self.ids["dos_mixed"].algorithm = DoSAlgorithm.MIXED
        self.ids["dos_dh2"].algorithm = DoSAlgorithm.DARK_HERESY_2

        # load character
        global CHARACTER
        CHARACTER = JsonStore(user_dir / "character.json")
        if not CHARACTER.exists("character"):
            CHARACTER.put("character", **default_character)
        # CHARACTER.put("character", **default_character)
        self.character = CHARACTER.get("character")
        start_layout = StartLayout(self.data)
        self.ids["all_talents"].add_widget(start_layout)

        # set characteristics
        for key in characteristics.keys():
            self.ids[key].set_text(self.character["characteristics"][key])
            self.ids[key].key = self.data["characteristics"][key]["name"]
            self.ids[key].value = self.character["characteristics"][key][0]
            self.ids[key].bind(
                on_press=lambda inst: TestPopup(inst.key, inst.value))

        # add skills to the charakter screen
        self.ids["skill_box"].height = 0
        bg = True
        self.skill_box_dict = {}
        for key, skill in self.data["skills"].items():
            if skill["skill_group"]:
                skill_group_box_dict = {}
                if key in self.character["skills"]:
                    for skill_group, status in self.character["skills"][
                            key].items():
                        box = SkillBox(
                            skill,
                            self.data["characteristics"][
                                skill["characteristic"]]["short"],
                            self.character["characteristics"][
                                skill["characteristic"]][0],
                            status,
                            bg,
                            name="{} ({})".format(skill["name"], skill_group),
                        )
                        bg = not bg
                        self.ids["skill_box"].height += box.height
                        self.ids["skill_box"].add_widget(box)
                        skill_group_box_dict[skill_group] = box
                else:
                    box = SkillBox(
                        skill,
                        self.data["characteristics"][skill["characteristic"]]
                        ["short"],
                        self.character["characteristics"][
                            skill["characteristic"]][0],
                        None,
                        bg,
                        name="{} ()".format(skill["name"]),
                    )
                    bg = not bg
                    self.ids["skill_box"].height += box.height
                    self.ids["skill_box"].add_widget(box)
                self.skill_box_dict[key] = skill_group_box_dict
            else:
                box = SkillBox(
                    skill,
                    self.data["characteristics"][
                        skill["characteristic"]]["short"],
                    self.character["characteristics"][skill["characteristic"]]
                    [0],
                    self.character["skills"][key]
                    if key in self.character["skills"].keys() else None,
                    bg,
                )
                bg = not bg
                self.ids["skill_box"].height += box.height
                self.ids["skill_box"].add_widget(box)
                self.skill_box_dict[key] = box

        # add talents to the character screen
        for talent in self.character["talents"]:
            if type(talent) == list:
                key = talent[0]
                groups = talent[1:]
            else:
                key = talent
                groups = []
            button = TalentButton(
                key=key,
                text=f'{self.data["talents"][key]["name"]}'
                if len(groups) == 0 else
                f'{self.data["talents"][key]["name"]} ({", ".join(groups)})',
            )
            button.bind(on_press=lambda b: TalentInfoPopup(self.data["talents"]
                                                           [b.key]))
            self.ids["talents_box"].add_widget(button)
            self.ids["talents_box"].height += button.height

            # handle talented
            if key == "talented":
                for skill in groups:
                    for skill_key, skill_data in self.data["skills"].items():
                        if skill_data["name"] == skill:
                            break
                    self.skill_box_dict[skill_key].skill_value += 10
                    self.skill_box_dict[skill_key].modifier_list.append({
                        "name":
                        f"Talented ({skill})",
                        "bonus":
                        10,
                        "type":
                        "talent",
                        "on":
                        True,
                    })
        self.ids["talents_box"].children.sort()

        # add implants to the character srceen
        self.ids["implants_box"].height = 0
        for implant in self.character["implants"]:
            modifier_list = []
            for modifier in self.data["implants"][implant["key"]]["bonus"]:
                modifier_list.append(
                    [self.skill_box_dict[modifier[0]], modifier[1]])
            implant_box = ImplantBox(
                self.data["implants"][implant["key"]],
                implant["on"],
                implant["quality"],
                modifier_list,
            )
            self.ids["implants_box"].add_widget(implant_box)
            self.ids["implants_box"].height += implant_box.height

        # add weapons to the battle screen
        for weapon in self.character["weapons"]:
            weapon_box = WeaponBox(
                weapon,
                self.character["characteristics"]["ws"][0],
                self.character["characteristics"]["bs"][0],
                self.character["characteristics"]["s"][0],
                self.skill_box_dict["dodge"].skill_value,
            )
            self.ids["weapon_box"].add_widget(weapon_box)
            self.ids["weapon_box"].height += weapon_box.height

        # set wounds
        self.ids["wounds_max"].text = str(
            self.character["status"]["wounds"]["max"])
        self.ids["wounds_current"].text = str(
            self.character["status"]["wounds"]["current"])
        self.ids["wounds_critical"].text = str(
            self.character["status"]["wounds"]["critical"])
        self.ids["button_take_damage"].bind(
            on_press=lambda _: TakeDamagePopup(self))
        self.ids["button_heal"].bind(on_press=lambda _: HealDamagePopup(self))

        # set fatigue
        self.ids["fatigue_current"].text = str(
            self.character["status"]["fatigue"])
        self.ids["fatigue_max"].text = str(
            self.character["characteristics"]["t"][0] // 10)

        # set fate points
        self.ids["fate_max"].text = str(
            self.character["status"]["fate"]["max"])
        self.ids["fate_current"].text = str(
            self.character["status"]["fate"]["current"])
class AssetsEditorPopupAdd():

    # 0.5.0 TEST EVENTS
    def on_mouse_pos(self, window, pos):
        for item in self.leftBox.children:
            print("MOUSE EVENTS >>>>>>>>" + item.__class__.__name__)
            if item.__class__.__name__ == "Button":
                if item.collide_point(*pos):
                    print('POINT :::>>:' + item.text)
                    item.background_color =(self.engineConfig.getThemeTextColor())
                    item.color = (self.engineConfig.getThemeCustomColor('engineBtnsBackground'))
                else:
                    item.color = (self.engineConfig.getThemeTextColor())
                    item.background_color = (self.engineConfig.getThemeCustomColor('engineBtnsBackground'))
                    # do something here

    def __init__(self, **kwargs):

        self.engineConfig = kwargs.get("engineConfig")
        self.engineRoot = kwargs.get("engineRoot")
        self.currentAsset = kwargs.get("currentAsset")

        Window.bind(mouse_pos=self.on_mouse_pos)

        self.operationStatus = True
        self.isFreeRigthBox = True

        self.box = BoxLayout(orientation="horizontal")
        self.leftBox = BoxLayout(orientation="vertical")
        self.imageResourceGUIBox = BoxLayout(orientation="vertical")

        print("DEBUG", platform)

        if platform == 'linux':
            drives = psutil.disk_partitions()

        if platform == 'win':
            drives = ['%s:' % d for d in string.ascii_uppercase if os.path.exists('%s:' % d)]

        for item in drives:
            print(item)

        self.drivesChooseBox = BoxLayout(size_hint=(1, None),  height=40,)
        for item in drives:
            if platform == 'win':
                self.drivesChooseBox.add_widget(Button(
                    text=item + '/',
                    on_press=partial(self.setFileBrowserPath),
                            color=(self.engineConfig.getThemeTextColor()),
                        size_hint=(1, None),  height=65,
                        background_normal= '',
                        background_color=(self.engineConfig.getThemeCustomColor('engineBtnsBackground'))
                ))
                print(" drive: ", item)
            elif platform == 'linux' or True:
                self.drivesChooseBox.add_widget(Button(
                    text=item.mountpoint ,
                    on_press=partial(self.setFileBrowserPath),
                            color=(self.engineConfig.getThemeTextColor()),
                        size_hint=(1, None),  height=65,
                        background_normal= '',
                        background_color=(self.engineConfig.getThemeCustomColor('engineBtnsBackground'))
                ))
                print(" drive: ", item)


        self.imageResourceGUIBox.add_widget(self.drivesChooseBox)

        if platform == 'win':
            self.fileBrowser = FileChooserListView(# select_string='Select', dirselect: True
                # path='projects/' + self.engineConfig.currentProjectName + '/data/',
                filters=['*.png', '*.jpg'],
                path= drives[0] + '/',
                size_hint=(1,3),
                dirselect= True,
                on_submit=self.load_from_filechooser
            )
        elif platform == 'linux' or True:
            self.fileBrowser = FileChooserListView(# select_string='Select', dirselect: True
                # path='projects/' + self.engineConfig.currentProjectName + '/data/',
                filters=['*.png', '*.jpg'],
                path= drives[0].mountpoint + '/',
                size_hint=(1,3),
                dirselect= True,
                on_submit=self.load_from_filechooser
            )
            
        self.imageResourceGUIBox.add_widget(self.fileBrowser)
        self.fileBrowser.bind(selection=partial(self.load_from_filechooser))

        self.imageResourceGUIBox.add_widget(Label(text='Application assets pack path' , size_hint=(1, None),  height=40 ), )
        self.selectedPathLabel = Label(text='...')
        self.imageResourceGUIBox.add_widget(self.selectedPathLabel)

        self.assetName = TextInput( text='MyAssets1', foreground_color=(0,1,1, 1),
                                    size_hint=(1, None),  height=40)
        with self.assetName.canvas.before:
            Color(self.engineConfig.getThemeCustomColor('background')[0],
                     self.engineConfig.getThemeCustomColor('background')[1],
                     self.engineConfig.getThemeCustomColor('background')[2],
                     self.engineConfig.getThemeCustomColor('background')[3])
            self.assetName.rect = Rectangle(size=self.assetName.size,
                                            pos=self.assetName.pos)
        def update_rect(instance, value):
            instance.rect.pos = instance.pos
            instance.rect.size = instance.size

        self.imageResourceGUIBox.add_widget(self.assetName)

        # self.assetName.bind(pos=update_rect, size=update_rect)

        self.assetName.foreground_color = (1,1,1,1)

        self.commandBtn = Button(text='Add selected image',
                                 color=(self.engineConfig.getThemeTextColor()),
                                 size_hint=(1, None),  height=60,
                                 background_normal= '',
                                 background_color=(self.engineConfig.getThemeCustomColor('engineBtnsBackground')) )
                                 #on_press=partial(self.createImageAssets))
        self.commandBtn.bind(on_press=partial(self.createImageAssets))

        self.imageResourceGUIBox.add_widget(self.commandBtn)

        self.leftBox.add_widget(Label(text='Application assets package operation.'))
        self.cancelBtn = Button(text='Cancel',
                                color=(self.engineConfig.getThemeTextColor()),
                                size_hint=(1, None),  height=70,
                                background_normal= '',
                                background_color=(self.engineConfig.getThemeCustomColor('engineBtnsBackground')))

        self.previewBox = BoxLayout(size_hint=(1,None), height=250)
        self.previewPicture = AsyncImage(source="", size_hint=(1, 1))
        self.previewBox.add_widget(Label(text='Preview Box'))
        self.previewBox.add_widget(self.previewPicture)

        self.imageResourceGUIBox.add_widget(self.previewBox)

        self.box.add_widget(self.leftBox)

        # Add button  - ImageResource
        self.addImageRes = Button(markup=True, text='[b]Add Image Resource[b]',
                                color=(self.engineConfig.getThemeTextColor()),
                                size_hint=(1, None),  height=60,
                                background_normal= '',
                                background_color=(self.engineConfig.getThemeCustomColor('engineBtnsBackground')))
        
                                

        self.leftBox.add_widget(self.addImageRes)

        # Others  - Fonts
        self.addFontRes = Button(markup=True, text='[b]Add Font Resource[b]',
                                color=(self.engineConfig.getThemeTextColor()),
                                size_hint=(1, None),  height=60,
                                background_normal= '',
                                background_color=(self.engineConfig.getThemeCustomColor('engineBtnsBackground')))

        # Add JSON Data  - JSONResource
        self.addJSONResBtn = Button(markup=True, text='[b]Add JSON DATA Resource[b]',
                                color=(self.engineConfig.getThemeTextColor()),
                                size_hint=(1, None),  height=60,
                                background_normal= '',
                                background_color=(self.engineConfig.getThemeCustomColor('engineBtnsBackground')))

        self.leftBox.add_widget(self.addJSONResBtn)
        self.leftBox.add_widget(self.addFontRes)
        self.leftBox.add_widget(self.cancelBtn)

        self.previewFont = Label(
                                  size_hint=(1, 1),
                                  markup=True,
                                  font_size=50,
                                  text="Font [b]Bold[/b]!")

        _local = 'CrossK ' + self.engineConfig.getVersion() + ' Assets Editor'
        self.popup = Popup(title=_local , content=self.box, auto_dismiss=False)

        self.cancelBtn.bind(on_press=self.popup.dismiss)
        self.addImageRes.bind(on_press=lambda a:self.showImageAssetGUI())
        self.addFontRes.bind(on_press=lambda a:self.showFontAssetGUI())
        self.addJSONResBtn.bind(on_press=lambda a:self.showJSONAssetGUI())

        self.popup.open()

    def showImageAssetGUI(self):
        # no prepare it si initial
        if self.isFreeRigthBox == True:
            self.box.add_widget(self.imageResourceGUIBox)
            self.isFreeRigthBox = False

            self.previewPicture.size_hint = (1,1)
            self.previewFont.size_hint = (0,0)

    def showFontAssetGUI(self):
        if self.isFreeRigthBox == True:
            # prepare
            self.fileBrowser.filters = ['*.ttf']
            self.commandBtn.text = 'Add Font Family'
            self.commandBtn.unbind(on_press=partial(self.createImageAssets)),
            self.commandBtn.bind(on_press=partial(self.createFontAssets))

            self.previewPicture.size_hint = (0,0)
            self.previewFont.size_hint = (1,1)

            self.box.add_widget(self.imageResourceGUIBox)
            self.isFreeRigthBox = False

    def showJSONAssetGUI(self):
        if self.isFreeRigthBox == True:
            # prepare
            self.fileBrowser.filters = ['*.json']
            self.commandBtn.text = 'Add JSON Object Data'

            self.commandBtn.unbind(on_press=partial(self.createImageAssets)),
            self.commandBtn.bind(on_press=partial(self.createJSONAssets))

            self.previewPicture.size_hint = (0,0)
            # self.previewFont.size_hint = (0,0)

            self.box.add_widget(self.imageResourceGUIBox)
            self.isFreeRigthBox = False

    def resolvePathFolder(self):
        ASSETPACK_PATH = os.path.abspath(
          os.path.join(os.path.dirname(__file__), '../../projects/' + self.engineConfig.currentProjectName + "/data/")
        )
        if not os.path.exists(ASSETPACK_PATH):
            print("MAKE_ASSETPACK_PATH")
            os.mkdir(ASSETPACK_PATH)
        else:
            print('ASSETPACK_EXIST')

    def resolveAssetPathFolder(self, typeOfAsset):

        CURRENT_ASSETPACK_PATH = os.path.abspath(
          os.path.join(os.path.dirname(__file__), '../../projects/' + self.engineConfig.currentProjectName + "/data/" + self.assetName.text)
        )

        collectExt = ''
        local = self.fileBrowser.selection[0][::-1]
        for item in local:
            if item == '.':
                print("Create Image Resource -> Break EXT = ", collectExt)
                break
            else:
                collectExt += item;
        collectExt = collectExt[::-1]
        # print(collectExt)

        if not os.path.exists(CURRENT_ASSETPACK_PATH):
            print("MAKE_ASSETS_PACK_DIR")
            os.mkdir(CURRENT_ASSETPACK_PATH)
        else:
            if self.currentAsset == None:
                print("SOMETHIND WRONG - ASSETS ALREADY EXIST")
                getMessageBoxYesNo(
                    message="Asset reference path with this name already exist. Please use some different name.",
                    msgType="OK")
                    #callback=wtf)
                return None

        self.operationStatus = False
        print("Assets pack write meta data...")
        copyfile(self.fileBrowser.selection[0], CURRENT_ASSETPACK_PATH + '/' + str(self.assetName.text) + '.' + collectExt)
        self.assetsStore = JsonStore(self.engineConfig.currentProjectAssetPath+ '/assets.json')
        localElements = self.assetsStore.get('assetsComponentArray')['elements']

        asset = {
            'name': self.assetName.text,
            'type': typeOfAsset,
            'ext': collectExt,
            'source': CURRENT_ASSETPACK_PATH + '/' + str(self.assetName.text) + '.' + collectExt,
            'path': 'projects/' + self.engineConfig.currentProjectName + "/data/"+ str(self.assetName.text) + "/" + str(self.assetName.text) + "." + collectExt,
            'version': self.engineConfig.getVersion()
        }

        # Check it if exist
        localCheckDouble = False
        for checkItem in localElements:
            if checkItem['name'] == asset['name']:
                localCheckDouble = True
                getMessageBoxYesNo(
                    message="Asset reference with this name already exist. Please use some different name.",
                    msgType="OK")
                    #callback=wtf)
        if localCheckDouble == False:
            localElements.append(asset)
            self.assetsStore.put('assetsComponentArray', elements=localElements)
            self.engineRoot.resourceGUIContainer.selfUpdate()

    def createImageAssets(self, instance):
        if self.operationStatus == True:
            self.resolvePathFolder()
            self.resolveAssetPathFolder('ImageResource')
            self.popup.dismiss()

    def createFontAssets(self, instance):
        if self.operationStatus == True:
            self.resolvePathFolder()
            self.resolveAssetPathFolder('FontResource')
            self.popup.dismiss()

    def createJSONAssets(self, instance):
        if self.operationStatus == True:
            self.resolvePathFolder()
            self.resolveAssetPathFolder('JSONResource')
            self.popup.dismiss()

    def load_from_filechooser(self, instance , selectedData):
        print("Selected data: ", selectedData)
        #self.load(self.fileBrowser.path, self.fileBrowser.selection)
        localHandler = self.fileBrowser.selection[0].replace(self.fileBrowser.path, '')

        self.selectedPathLabel.text = localHandler

        # check type assets
        print(">>", self.fileBrowser.filters)
        if self.fileBrowser.filters[0] ==  '*.png' or self.fileBrowser.filters[0] == '*.jpg':
            self.previewPicture.source=self.fileBrowser.selection[0]

        # JSON Nidza
        if '.json' in localHandler:
            self.imageResourceGUIBox.remove_widget(self.previewBox)

            testJSONNidzaLOader = JsonN(
                    assetsPath=self.fileBrowser.selection[0],
                    currentContainer=self.imageResourceGUIBox,
                    engineRoot=self.engineRoot
                )

    def setFileBrowserPath(self, instance):
        self.fileBrowser.path = instance.text
        print( 'setFileBrowserPath: ' , instance.text)
 def save_data(self):
     Logger.info("Data: Saving data...")
     store = JsonStore(os.path.join(data_dir, 'data.json'))
     for k in self.data.keys():
         store.put(k, val=str(self.data[k]))
     Logger.info("Data: Saving data done")
Beispiel #48
0
from kivy.core.window import Window
from random import randint
from kivy.uix.image import Image
from math import radians, cos, sin, sqrt
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition
from kivy.core.audio import SoundLoader
from kivy.storage.jsonstore import JsonStore
from os.path import join

data_dir = App().user_data_dir

store = JsonStore(join(data_dir, 'store.json'))
try:
    store.get('highscore')
except KeyError:
    store.put('highscore', best=0)

circle_path = 'images/icon.png'
white_circle_path = 'images/white_circle.png'
grey_circle_path = 'images/grey_circle.png'
big_grey_circle_path = 'images/big_grey_circle.png'
big_orange_circle_path = 'images/orange_big_circle.png'

music_sound = SoundLoader.load('sounds/360music.wav')
win_sound = SoundLoader.load('sounds/360winsound.wav')
lose_sound = SoundLoader.load('sounds/360losesound.wav')
click_sound = SoundLoader.load('sounds/360clicksound.wav')
highscore_sound = SoundLoader.load('sounds/360highscoresound.wav')

size = Window.size
window_x = (size[0])
Beispiel #49
0
class AssetsEditorPopup():
    def __init__(self, **kwargs):

        self.engineConfig = kwargs.get("engineConfig")
        self.currentAsset = kwargs.get("currentAsset")
        self.engineRoot = kwargs.get("engineRoot")
        self.assetsStore = JsonStore('projects/' +
                                     self.engineConfig.currentProjectName +
                                     '/data/assets.json')

        self.isFreeRigthBox = True
        self.box = BoxLayout(orientation="horizontal")

        self.leftBox = BoxLayout(orientation="vertical")
        self.imageResourceGUIBox = BoxLayout(orientation="vertical")

        if platform == 'linux':
            drives = psutil.disk_partitions()

        if platform == 'win':
            drives = [
                '%s:' % d for d in string.ascii_uppercase
                if os.path.exists('%s:' % d)
            ]

        self.drivesChooseBox = BoxLayout(
            size_hint=(1, None),
            height=40,
        )
        for item in drives:
            if platform == 'win':
                self.drivesChooseBox.add_widget(
                    Button(text=item + '/',
                           on_press=partial(self.setFileBrowserPath),
                           color=(self.engineConfig.getThemeTextColor()),
                           size_hint=(1, None),
                           height=65,
                           background_normal='',
                           background_color=(
                               self.engineConfig.getThemeCustomColor(
                                   'engineBtnsBackground'))))
                print(" drive: ", item)
            elif platform == 'linux' or True:
                self.drivesChooseBox.add_widget(
                    Button(text=item.mountpoint,
                           on_press=partial(self.setFileBrowserPath),
                           color=(self.engineConfig.getThemeTextColor()),
                           size_hint=(1, None),
                           height=65,
                           background_normal='',
                           background_color=(
                               self.engineConfig.getThemeCustomColor(
                                   'engineBtnsBackground'))))
                print(" drive: ", item)

        self.imageResourceGUIBox.add_widget(self.drivesChooseBox)

        if platform == 'win':
            self.fileBrowser = FileChooserListView(
                # Can be added default optimal engine config initial dir
                # select_string='Select', dirselect: True
                # path='projects/' + self.engineConfig.currentProjectName + '/data/',
                filters=['*.png', '*.jpg'],
                path=drives[1] + '/',
                size_hint=(1, 3),
                dirselect=False,
                on_submit=self.load_from_filechooser)
        elif platform == 'linux' or True:
            self.fileBrowser = FileChooserListView(  # select_string='Select', dirselect: True
                # path='projects/' + self.engineConfig.currentProjectName + '/data/',
                filters=['*.png', '*.jpg'],
                path=drives[0].mountpoint + '/',
                size_hint=(1, 3),
                dirselect=True,
                on_submit=self.load_from_filechooser)

        self.imageResourceGUIBox.add_widget(self.fileBrowser)
        self.fileBrowser.bind(selection=partial(self.load_from_filechooser))

        self.imageResourceGUIBox.add_widget(
            Label(text='Application assets full source path:',
                  size_hint=(1, None),
                  height=40,
                  font_size=15))
        self.selectedPathLabel = Label(text='...',
                                       size_hint=(1, None),
                                       height=40,
                                       font_size=9,
                                       underline=True)
        self.imageResourceGUIBox.add_widget(self.selectedPathLabel)

        self.imageResourceGUIBox.add_widget(
            Label(text='Application assets relative path:',
                  size_hint=(1, None),
                  height=40))

        self.selectedRelativePathLabel = Button(
            text='...',
            size_hint=(1, None),
            height=40,
            font_size=12,
            underline=True,
            on_press=partial(self.copyToClipBoard),
            color=(self.engineConfig.getThemeTextColor()),
            background_normal='',
            background_color=(
                self.engineConfig.getThemeCustomColor('engineBtnsBackground')),
        )

        self.imageResourceGUIBox.add_widget(self.selectedRelativePathLabel)

        self.assetNameGUINAme = Label(
            text='Name of assets reference (READ ONLY)',
            color=(self.engineConfig.getThemeTextColor()),
            font_size=15,
            size_hint=(1, None),
            height=40)

        self.imageResourceGUIBox.add_widget(self.assetNameGUINAme)

        self.assetName = Label(text='MyAssets1',
                               color=(self.engineConfig.getThemeTextColor()),
                               font_size=12,
                               underline=True,
                               size_hint=(1, None),
                               height=40)

        with self.assetName.canvas.before:
            Color(
                self.engineConfig.getThemeCustomColor('warn')[0],
                self.engineConfig.getThemeCustomColor('warn')[1],
                self.engineConfig.getThemeCustomColor('warn')[2],
                self.engineConfig.getThemeCustomColor('warn')[3])
            self.assetName.rect = Rectangle(size=self.assetName.size,
                                            pos=self.assetName.pos)

        def update_rect(instance, value):
            instance.rect.pos = instance.pos
            instance.rect.size = instance.size

        self.imageResourceGUIBox.add_widget(self.assetName)

        self.imageResourceGUIBox.add_widget(
            Button(text='Update selected image asset',
                   color=(self.engineConfig.getThemeTextColor()),
                   size_hint=(1, None),
                   height=65,
                   font_size=15,
                   bold=True,
                   background_normal='',
                   background_color=(self.engineConfig.getThemeCustomColor(
                       'engineBtnsBackground')),
                   on_press=partial(self.createImageAssets)))

        self.leftBox.add_widget(
            Label(text='CrossK assets editor',
                  size_hint=(1, None),
                  height=220,
                  font_size=25,
                  bold=True))

        assetListHeder = BoxLayout(size_hint=(1, None), height=80)

        titleText = Label(text='Assets List.',
                          color=(self.engineConfig.getThemeTextColor()),
                          font_size=25,
                          bold=True,
                          padding_x=0,
                          padding_y=0,
                          center=(1, 1),
                          size_hint_x=1,
                          size_hint_y=1,
                          height=60)
        with titleText.canvas.before:
            Color(self.engineConfig.getThemeBgSceneBtnColor())
            titleText.rect = Rectangle(size=titleText.size, pos=titleText.pos)

        def update_rect(instance, value):
            instance.rect.pos = instance.pos
            instance.rect.size = instance.size

        self.leftBox.add_widget(titleText)
        titleText.bind(pos=update_rect, size=update_rect)

        headerSelector = Label(
            text='Selector',
            color=(self.engineConfig.getThemeTextColor()),
            font_size=15,  # add
            bold=True,  # add
            padding_x=0,  # test
            padding_y=0,  # test
            center=(1, 1),  # test
            font_blended=True,
            size_hint_x=1,
            size_hint_y=None,
            height=40)
        with headerSelector.canvas.before:
            Color(
                self.engineConfig.getThemeTextColorByComp('background')['r'],
                self.engineConfig.getThemeTextColorByComp('background')['g'],
                self.engineConfig.getThemeTextColorByComp('background')['b'])
            headerSelector.rect = Rectangle(size=headerSelector.size,
                                            pos=headerSelector.pos)

        def update_rect(instance, value):
            instance.rect.pos = instance.pos
            instance.rect.size = instance.size

        headerSelector.bind(pos=update_rect, size=update_rect)
        assetListHeder.add_widget(headerSelector)

        headerPreview = Label(
            text='Preview',
            color=(self.engineConfig.getThemeTextColor()),
            font_size=15,  # add
            bold=True,  # add
            padding_x=0,  # test
            padding_y=0,  # test
            center=(1, 1),  # test
            font_blended=True,
            size_hint_x=0.3,
            size_hint_y=None,
            height=40)
        with headerPreview.canvas.before:
            Color(
                self.engineConfig.getThemeTextColorByComp('background')['r'],
                self.engineConfig.getThemeTextColorByComp('background')['g'],
                self.engineConfig.getThemeTextColorByComp('background')['b'])
            headerPreview.rect = Rectangle(size=headerPreview.size,
                                           pos=headerPreview.pos)

        def update_rect(instance, value):
            instance.rect.pos = instance.pos
            instance.rect.size = instance.size

        headerPreview.bind(pos=update_rect, size=update_rect)

        assetListHeder.add_widget(headerPreview)

        headerDelete = Label(
            text='Note: No undo operation',
            color=(self.engineConfig.getThemeTextColor()),
            font_size=15,  # add
            bold=True,  # add
            padding_x=0,  # test
            padding_y=0,  # test
            center=(1, 1),  # test
            font_blended=True,
            size_hint_x=1,
            size_hint_y=None,
            height=40)
        with headerDelete.canvas.before:
            Color(
                self.engineConfig.getThemeTextColorByComp('background')['r'],
                self.engineConfig.getThemeTextColorByComp('background')['g'],
                self.engineConfig.getThemeTextColorByComp('background')['b'])
            headerDelete.rect = Rectangle(size=headerDelete.size,
                                          pos=headerDelete.pos)

        def update_rect(instance, value):
            instance.rect.pos = instance.pos
            instance.rect.size = instance.size

        headerDelete.bind(pos=update_rect, size=update_rect)
        assetListHeder.add_widget(headerDelete)

        self.leftBox.add_widget(assetListHeder)

        loadAssetElements = self.assetsStore.get(
            'assetsComponentArray')['elements']

        self.sceneScroller = ScrollView(size_hint=(1, None),
                                        size=(500, 650),
                                        pos_hint={
                                            'center_x': 0.5,
                                            'top': 0
                                        })
        self.selfUpdate(loadAssetElements)

        self.leftBox.add_widget(self.sceneScroller)

        fillSpace = Label(text='---', size_hint=(1, 0.3))
        with fillSpace.canvas.before:
            Color(
                self.engineConfig.getThemeTextColorByComp('background')['r'],
                self.engineConfig.getThemeTextColorByComp('background')['g'],
                self.engineConfig.getThemeTextColorByComp('background')['b'])
            fillSpace.rect = Rectangle(size=fillSpace.size, pos=fillSpace.pos)

        def update_rect(instance, value):
            instance.rect.pos = instance.pos
            instance.rect.size = instance.size

        self.leftBox.add_widget(fillSpace)
        fillSpace.bind(pos=update_rect, size=update_rect)

        self.cancelBtn = Button(
            text='Cancel',
            color=(self.engineConfig.getThemeTextColor()),
            size_hint=(1, None),
            height=70,
            background_normal='',
            background_color=(
                self.engineConfig.getThemeCustomColor('engineBtnsBackground')))

        self.previewBox = BoxLayout(size_hint=(1, None), height=250)
        self.previewPicture = AsyncImage(source="", size_hint=(1, 1))
        self.previewFont = Label(size_hint=(1, 1),
                                 markup=True,
                                 font_size=50,
                                 text="Font [b]Bold[/b]!")
        self.previewBox.add_widget(
            Label(text='Preview Box', bold=True, font_size=15))
        self.previewBox.add_widget(self.previewPicture)
        self.previewBox.add_widget(self.previewFont)

        self.imageResourceGUIBox.add_widget(self.previewBox)

        self.box.add_widget(self.leftBox)

        self.leftBox.add_widget(self.cancelBtn)

        _local = 'CrossK ' + self.engineConfig.getVersion() + ' Assets Editor'
        self.popup = Popup(title=_local, content=self.box, auto_dismiss=False)
        self.cancelBtn.bind(on_press=self.popup.dismiss)
        self.popup.open()

    def showAssetGUI(self, item, instance):

        if (platform == 'win'):
            transformPath = item['path'].replace('/', '\\')
        else:
            transformPath = item['path']

        if item['type'] == 'ImageResource':
            if self.isFreeRigthBox == True:
                self.box.add_widget(self.imageResourceGUIBox)
                self.isFreeRigthBox = False
            self.assetName.text = item['name']
            self.selectedPathLabel.text = item['source']
            self.selectedRelativePathLabel.text = item['path']
            self.previewPicture.source = transformPath
            self.previewFont.size_hint = (0, 0)
            self.previewPicture.size_hint = (1, 1)
        elif item['type'] == 'FontResource':
            if self.isFreeRigthBox == True:
                self.box.add_widget(self.imageResourceGUIBox)
                self.isFreeRigthBox = False
            self.assetName.text = item['name']
            self.selectedPathLabel.text = item['source']
            self.selectedRelativePathLabel.text = item['path']
            self.previewPicture.size_hint = (0, 0)
            self.previewPicture.size = (5, 5)
            self.previewFont.text = "Font [b]Bold[/b]!"
            self.previewFont.size_hint = (1, 1)
            self.previewFont.font_name = item['path']
        elif item['type'] == 'JSONResource':
            self.fileBrowser.filters = ["*.json"]
            if self.isFreeRigthBox == True:
                self.box.add_widget(self.imageResourceGUIBox)
                self.isFreeRigthBox = False
            self.assetName.text = item['name']
            self.selectedPathLabel.text = item['source']
            self.selectedRelativePathLabel.text = item['path']
            self.previewPicture.size_hint = (0, 0)
            self.previewPicture.size = (5, 5)
            self.previewFont.size_hint = (1, 1)
            # nikola 0.5.0
            localStore = JsonStore(item['path'])
            print(">>>>>>>>>>>>>>>" + localStore.get('name'))
            self.previewFont.font_size = "10"
            self.previewFont.text = "JSON root keys: \n "
            for key in localStore._data.keys():
                self.previewFont.text += " " + key + "\n"
                #  localStore.get('name')
                print(key)

    def copyToClipBoard(self, instance):
        Clipboard.copy(self.selectedRelativePathLabel.text)
        print('Copied to clipboard.')

    def resolvePathFolder(self):
        ASSETPACK_PATH = os.path.abspath(
            os.path.join(
                os.path.dirname(__file__), '../../projects/' +
                self.engineConfig.currentProjectName + "/data/"))
        if not os.path.exists(ASSETPACK_PATH):
            print("MAKE_ASSETPACK_PATH")
            os.mkdir(ASSETPACK_PATH)
        else:
            print('ASSETPACK_EXIST')

    def resolveAssetPathFolder(self):

        if len(self.fileBrowser.selection) == 0:

            def wtf():
                print('wtf')

            getMessageBoxYesNo(
                message="Nothing to update. Please select new source file.",
                msgType="OK",
                callback=wtf)
            return 0

        CURRENT_ASSETPACK_PATH = os.path.abspath(
            os.path.join(
                os.path.dirname(__file__),
                '../../projects/' + self.engineConfig.currentProjectName +
                "/data/" + self.assetName.text))

        collectExt = ''
        print("Create Image Resource ->")
        local = self.fileBrowser.selection[0][::-1]
        for item in local:
            if item == '.':
                print("Create Image Resource -> Break EXT = ", collectExt)
                break
            else:
                collectExt += item
        collectExt = collectExt[::-1]
        print(collectExt)

        if not os.path.exists(CURRENT_ASSETPACK_PATH):
            print("MAKE ASSETS PACK DIR")
            os.mkdir(CURRENT_ASSETPACK_PATH)
        else:
            if self.currentAsset == None:
                print('current asset need load')
                print("SOMETHIND WRONG - ASSETS ALREADY EXIST")
                return None

        print("Assets pack write meta data.")

        copyfile(
            self.fileBrowser.selection[0], CURRENT_ASSETPACK_PATH + '/' +
            str(self.assetName.text) + '.' + collectExt)
        self.assetsStore = JsonStore(
            self.engineConfig.currentProjectAssetPath + '/assets.json')
        localElements = self.assetsStore.get(
            'assetsComponentArray')['elements']

        ########################
        # Must be detail show
        if self.currentAsset != None:
            print('# Must be detail show')

        ########################
        asset = {
            'name':
            self.assetName.text,
            'type':
            'ImageResource',
            'ext':
            collectExt,
            'source':
            CURRENT_ASSETPACK_PATH + '/' + str(self.assetName.text) + '.' +
            collectExt,
            'path':
            'projects/' + self.engineConfig.currentProjectName + "/data/" +
            str(self.assetName.text) + "/" + str(self.assetName.text) + "." +
            collectExt,
            'version':
            self.engineConfig.getVersion()
        }

        localCheckIsExist = False
        for _index, item in enumerate(localElements):
            if item['name'] == asset['name']:
                localCheckIsExist = True
                localElements[_index] = asset

        def catchErr1():
            print("catchErr1")

        if localCheckIsExist == True:
            self.assetsStore.put('assetsComponentArray',
                                 elements=localElements)
            # resourceGUIContainer
            self.popup.dismiss()
        else:
            getMessageBoxYesNo(
                message='Something wrong with updating asset name => ' +
                asset['name'],
                msgType='OK',
                callback=catchErr1)

    def createImageAssets(self, instance):
        print("Creating first assets ... ")
        # resolvePathFolder
        self.resolvePathFolder()
        self.resolveAssetPathFolder()

    def deleteAsset(self, item, instance):

        self.assetsStore = JsonStore('projects/' +
                                     self.engineConfig.currentProjectName +
                                     '/data/assets.json')
        currElements = self.assetsStore.get('assetsComponentArray')['elements']

        isDeleted = False
        for index, itemA in enumerate(currElements):
            if itemA['name'] == item['name']:
                currElements.pop(index)
                isDeleted = True
                self.assetsStore.put('assetsComponentArray',
                                     elements=currElements)
                break

        if isDeleted == True:
            self.engineRoot.resourceGUIContainer.selfUpdate()
            self.selfUpdate(currElements)
            rmtree('projects/' + self.engineConfig.currentProjectName +
                   '/data/' + item['name'])
        else:
            getMessageBoxYesNo(
                message="Something wrong with delete operation.",
                msgType="OK",
                callback=wtf)

    def load_from_filechooser(self, instance, selectedData):
        # Selector
        if str(self.fileBrowser.selection[0]).find('.png') != -1 or str(
                self.fileBrowser.selection[0]).find('.jpg') != -1:
            print("Found!")
        else:
            print("Not found!")
            return None
        self.selectedPathLabel.text = self.fileBrowser.selection[0]
        self.previewPicture.source = self.fileBrowser.selection[0]

    def setFileBrowserPath(self, instance):
        self.fileBrowser.path = instance.text
        print('Selected:', instance.text)

    def selfUpdate(self, loadAssetElements):

        alllocalBox = BoxLayout(size_hint=(1, None),
                                height=len(loadAssetElements) * 90,
                                orientation='vertical')
        for _index, item in enumerate(loadAssetElements):

            localBox = BoxLayout(size_hint=(1, None),
                                 height=90,
                                 orientation='horizontal')
            currentColor = (self.engineConfig.getThemeBgSceneBtnColor())
            if item['type'] == 'ImageResource':
                currentColor = (self.engineConfig.getThemeBgSceneBoxColor())

            localBox.add_widget(
                Button(markup=True,
                       halign="left",
                       valign="middle",
                       padding_x=10,
                       font_size=15,
                       text='[b]' + item['name'] + '[/b] [u][i]' +
                       item['type'] + '[/i][/u]',
                       color=self.engineConfig.getThemeTextColor(),
                       background_normal='',
                       background_color=currentColor,
                       on_press=partial(self.showAssetGUI, item),
                       size_hint=(1, None),
                       height=90))
            if item['type'] == 'ImageResource':
                localPrevListBox = AsyncImage(source=item['path'],
                                              size_hint=(0.4, None),
                                              height=90)
                with localPrevListBox.canvas.before:
                    Color(
                        self.engineConfig.getThemeCustomColor('background')[0],
                        self.engineConfig.getThemeCustomColor('background')[1],
                        self.engineConfig.getThemeCustomColor('background')[2],
                        self.engineConfig.getThemeCustomColor('background')[3])
                    localPrevListBox.rect = Rectangle(
                        size=localPrevListBox.size, pos=localPrevListBox.pos)

                def update_rect(instance, value):
                    instance.rect.pos = instance.pos
                    instance.rect.size = instance.size

                localPrevListBox.bind(pos=update_rect, size=update_rect)

                localBox.add_widget(localPrevListBox)
            elif item['type'] == 'FontResource':
                localBox.add_widget(
                    Label(font_name=item['path'],
                          size_hint=(0.4, None),
                          height=90,
                          text='Font'))
            elif item['type'] == 'JSONResource':
                localBox.add_widget(
                    Label(size_hint=(0.4, None), height=90, text='JSON DATA'))

            localBox.add_widget(
                Button(
                    markup=True,
                    halign="left",
                    valign="middle",
                    padding_x=10,
                    font_size=15,
                    text='[b]Delete[/b]',
                    color=(self.engineConfig.getThemeCustomColor("alert")),
                    background_normal='',
                    background_color=(
                        self.engineConfig.getThemeCustomColor('background')),
                    on_press=partial(self.deleteAsset, item),
                    size_hint=(1, None),
                    height=90))
            print('ADDED ', item)
            alllocalBox.add_widget(localBox)

        self.sceneScroller.clear_widgets()

        self.sceneScroller.add_widget(alllocalBox)
Beispiel #50
0
class MyScreenManager(ScreenManager):
    #ultimo = ""
    directorio = ''
    abierto = ""
    cargado = False
    modificando = False     # alta o modificando
    reg = 0
    claves_buscando = False # para saber quien listó las claves
    dic_items = {}          # {item: 'indice registro'}
    lista = []
    lista_claves = []
    listando_claves = False
    lista_claves_cargadas = False
    claves_seleccionadas = []
    eligiendo = False
    clave_nueva = False
    clave_renombrar = ""
    #pulsacion = False
    jstore = ""
    registros = [] # las lineas del fichero
    items = []
    memos = []
    claves = []  # lista de claves de cada registro [[cla1,cla2],[],...]
    #indice = []
    clave = []   # claves existentes
    num_lineas = StringProperty()
    #jstore = JsonStore("pim_store.json")
    #i_item = ObjectProperty()
    i_buscar_item = ObjectProperty()
    b_buscar_claves = ObjectProperty()
    #lis_panta = ObjectProperty()
    titulo_lista = StringProperty()
    titulo_fichero = StringProperty()
    panta = StringProperty()
    smBotonDeLista = BotonDeLista
    smBotonDeVocales = BotonDeVocales
    mayusculas = uppercase

    def __init__(self, **kwargs):
        super(MyScreenManager, self).__init__(**kwargs)
        self.current = 'sc_menu_principal'
        if platform == 'android': android.hide_keyboard()
        self.jstore = JsonStore("pim_store.json")
        try:
            ultimo = self.jstore.get("pim")['ultimo']
            self.directorio = self.jstore.get("pim")['directorio']
        except:
            return
        if not self.abrir_archivo(ultimo, incorporar=False, aviso=False):
            self.selec_archivo('Elegir archivo')
        log('año')
        log(u'año')

    def abrir_archivo(self, fich, incorporar, aviso=True):
        try:
            F = open(self.directorio + fich + FICH)
        except:
            if aviso: self.aviso('No puedo abrir ' + fich)
            return False
        if not incorporar: del self.registros[:]
        num_lineas = 0
        try:
            r = F.readline()
            while r:
                if len(r) > 2:
                    self.registros.append(r[:-1].decode('utf-8'))
                    #self.registros.append(r[:-1])
                    num_lineas += 1
                r = F.readline()
        except:
            self.aviso('No puedo leer ' + fich + ': ' + str(sys.exc_info()[0]))
            return False
        if not incorporar:
            self.abierto = fich
            self.titulo_fichero = fich
            self.num_lineas = str(num_lineas) if num_lineas else '0'
        else:
            self.num_lineas = str(int(self.num_lineas) + num_lineas)
        self.cargado = False
        return True

    def selec_archivo(self, opcion):
        #self.lista = [f[:-8] for f in listdir(getcwd()) if f[-8:]=='-PIM.csv']
        self.lista = [f[:-8] for f in listdir(self.directorio) if f[-8:]=='-PIM.csv']
        self.lista.sort()
        self.ids.lis_panta.adapter = ListAdapter(data=[], cls=BotonDeLista, args_converter=self.args_converter, selection_mode='single')
        self.listando_claves = False
        self.rellena("ficheros")
        self.titulo_lista = opcion
        self.ids.b_lista_izq.text = 'Menu'
        self.ids.b_lista_cen.text = ''
        self.ids.b_lista_der.text = ''
        self.ids.b_lista_over.text = 'Cancelar'
        self.current = 'sc_lista'

    def alta(self):
        if not self.cargado: self.carga_listas()
        self.ids.i_item_alta.text = ""
        self.ids.i_memo_alta.text = ""
        self.ids.i_claves_alta.text = ""
        self.modificando = False
        self.ids.i_item_alta.focus = True
        self.current = 'sc_alta'

    #def alta_clave(self, popup, cla):
        #if not cla: return
        #self.aviso(cla)
        #self.clave.append(cla)
        #self.clave.sort()
        #self.ids.i_claves_alta.text += ','+cla
        #popup.dismiss()
        #self.elige_claves('registro')

    def aviso(self, txt):
        the_content = Label(text = txt)
        the_content.color = (1,1,1,1)
        popup = Popup(title='PIM',
            content=the_content, size_hint_y=.25, title_align='center')
            #content = the_content, size_hint=(None, None), size=(350, 150))
        popup.open()

    def confirmacion(self, txt="", tema=""):
        def elim_1_reg(self):
            popup.dismiss()
            mapp.root.eliminar_registros(confirmado=True, modo='uno')
        def elim_n_reg(self):
            popup.dismiss()
            mapp.root.eliminar_registros(confirmado=True, modo='varios')
        def borr_fich(self):
            popup.dismiss()
            mapp.root.borrar_fich(confirmado=True, nombre=tema)
        def expor_exis(self):
            popup.dismiss()
            mapp.root.exportar_existente()
        def expor_nue(self):
            popup.dismiss()
            mapp.root.exportar_nuevo()
        def cancelar(self):
            popup.dismiss()
        cuerpo = Confirmacion(txt)
        cuerpo.color = (1,0,0,1)
        if tema == 'exportar':
            cuerpo.ids.b_aceptar.text = 'Añadir a existente'
            cuerpo.ids.b_cancelar.text = 'Archivo nuevo'
            cuerpo.ids.b_cancelar.bind(on_release=expor_nue)
        else:
            cuerpo.ids.b_aceptar.text = 'Aceptar'
            cuerpo.ids.b_cancelar.text = 'Cancelar'
            cuerpo.ids.b_cancelar.bind(on_release=cancelar)
        popup = Popup(title='CONFIRMACION',
            content=cuerpo, size_hint_y=.25, title_align='center',
            title_color=[1,0,0,1], auto_dismiss=False)
        if tema == 'elim_un_reg':
            cuerpo.ids.b_aceptar.bind(on_release=elim_1_reg)
        if tema == 'elim_n_regs':
            cuerpo.ids.b_aceptar.bind(on_release=elim_n_reg)
        if tema == 'exportar':
            cuerpo.ids.b_aceptar.bind(on_release=expor_exis)
        if tema.startswith('fichero-'):
            cuerpo.ids.b_aceptar.bind(on_release=borr_fich)
        popup.open()

    def dialogo(self, txt='', tema=''):
        def alta_clave(self):
            nueva = the_content.ids.i_dialog.text.strip()
            if not nueva: return
            mapp.root.clave.append(nueva)
            mapp.root.clave.sort()
            mapp.root.lista_claves.append(ClaveItem(text=nueva, is_selected=True))
            mapp.root.claves_seleccionadas.append(nueva)
            if mapp.root.ids.i_claves_alta.text:
                mapp.root.ids.i_claves_alta.text += ',' + nueva
            else:
                mapp.root.ids.i_claves_alta.text = nueva
            popup.dismiss()
            mapp.root.clave_nueva = True
            mapp.root.elige_claves('registro')
        def nuevo_fichero(self):
            popup.dismiss()
            mapp.root.fichero_nuevo(the_content.ids.i_dialog.text.strip())
        def exportar_fichero(self):
            popup.dismiss()
            mapp.root.exportar_nuevo(the_content.ids.i_dialog.text.strip())
        def renombre_clave(self):
            popup.dismiss()
            mapp.root.clave_nuevo_nombre(the_content.ids.i_dialog.text.strip())
        the_content = Dialogo(txt)
        the_content.color = (1,1,1,1)
        popup = Popup(title=txt,
            content=the_content, size_hint_y=.25, title_align='center', auto_dismiss=False)
        the_content.ids.b_cancelar.bind(on_release=popup.dismiss)
        if tema == 'clave':
            #~ the_content.ids.b_aceptar.bind(on_release=self.alta_clave(popup, the_content.ids.i_dialog.text))
            the_content.ids.b_aceptar.bind(on_release=alta_clave)
        elif tema == 'fichero_nuevo':
            the_content.ids.b_aceptar.bind(on_release=nuevo_fichero)
        elif tema == 'renombrar_clave':
            the_content.ids.b_aceptar.bind(on_release=renombre_clave)
        elif tema == 'fichero_exportar':
            the_content.ids.b_aceptar.bind(on_release=exportar_fichero)
        popup.open()

    def borrar_fich(self, confirmado, nombre):
        if not confirmado:
            self.confirmacion(u'¿Borrar el archivo ' + nombre + '?', 'fichero-'+nombre)
            return
        nombre = nombre[8:]
        try:
            remove(self.directorio + nombre + FICH)
            self.current = 'sc_menu_principal'
            self.aviso('Archivo borrado')
        except:
            self.aviso('Error al borrar archivo')

    def boton_lista_izq(self, texto):
        if self.titulo_lista == 'Claves':
            self.eligiendo = False
            if texto == 'Cancelar':
                self.current = 'sc_alta'
                return
        self.current = 'sc_menu_principal'
        #if texto == 'Menu': self.current = 'sc_menu_principal'

    def boton_lista_cen(self, texto):
        if self.titulo_lista.startswith('Registros encontrados'):
            #self.exportar()
            self.confirmacion('Opciones de exportación', 'exportar')
        elif self.titulo_lista == 'Claves':
            self.eligiendo = False
            if texto == 'Nueva':
                self.dialogo('Introduzca nueva clave', 'clave')
            else:
                self.current = 'sc_buscar'

    def boton_lista_der(self, texto):
        #~ self.ids.lis_panta._trigger_reset_populate()
        if self.titulo_lista.startswith('Registros encontrados'):
            self.current = 'sc_buscar'
        elif self.titulo_lista == 'Claves':
            self.eligiendo = False
            #~ cla_selec = [c.text for c in self.ids.lis_panta.adapter.data if c.is_selected]
            self.claves_seleccionadas.sort()
            if self.claves_buscando:
                self.ids.b_buscar_claves.text = ",".join(self.claves_seleccionadas)
                self.current = 'sc_buscar'
            else:
                self.ids.i_claves_alta.text = ",".join(self.claves_seleccionadas)
                self.current = 'sc_alta'

    def boton_lista_over(self, texto):
        if texto == 'Eliminar':
            self.eliminar_registros(confirmado=False, modo='varios')
        elif texto == 'Cancelar':
            self.current = 'sc_menu_principal'

    def busca(self):
        del self.lista[:]
        #self.dic_items = {}
        self.dic_items.clear()
        cad = self.i_buscar_cadena.text.lower()
        if self.ids.sw_ignora.active:
            cad = self.traduce(cad)
            if self.ids.cb_y.active:
                for i in range(len(self.items)):
                    if self.cadena_en_texto_ignora(i,cad) and self.clave_en_claves(i):
                        self.dic_items[self.repe(self.items[i])] = i
            else:
                for i in range(len(self.items)):
                    if self.cadena_en_texto_ignora(i,cad) or self.clave_en_claves(i):
                        self.dic_items[self.repe(self.items[i])] = i
        else:
            if self.ids.cb_y.active:
                for i in range(len(self.items)):
                    if self.cadena_en_texto(i,cad) and self.clave_en_claves(i):
                        self.dic_items[self.repe(self.items[i])] = i
            else:
                for i in range(len(self.items)):
                    if self.cadena_en_texto(i,cad) or self.clave_en_claves(i):
                        self.dic_items[self.repe(self.items[i])] = i
        self.lista = sorted(self.dic_items.keys(), reverse = True)
        #self.lista.sort()
        self.ids.lis_panta.adapter = ListAdapter(data=[], cls=BotonDeLista, args_converter=self.args_converter, selection_mode='single')
        self.titulo_lista = 'Registros encontrados: ' + str(len(self.lista))
        self.ids.b_lista_izq.text = 'Menu'
        self.ids.b_lista_cen.text = 'Exportar'
        self.ids.b_lista_der.text = 'Buscar'
        self.ids.b_lista_over.text = 'Eliminar'
        self.listando_claves = False
        self.rellena("items")
        self.current = 'sc_lista'

    def cadena_en_texto(self, i, cad):
        if cad:
            if self.ids.sw_busca.active:
                if not (self.items[i].lower().count(cad) or self.memos[i].lower().count(cad)):
                    return False
            else:
                if not self.items[i].lower().count(cad):
                    return False
        return True

    def cadena_en_texto_ignora(self, i, cad):
        if cad:
            if self.ids.sw_busca.active:
                if not (self.traduce(self.items[i].lower()).count(cad) or self.traduce(self.memos[i].lower()).count(cad)):
                    return False
            else:
                if not self.traduce(self.items[i].lower()).count(cad):
                    return False
        return True

    def clave_en_claves(self, i):
        #if self.b_buscar_claves.text != '<claves>':
        if self.b_buscar_claves.text != '':
            b_claves = self.b_buscar_claves.text.split(',')
            Y_claves = True
            if Y_claves:
                for c in b_claves:
                    if c not in self.claves[i]: return False
                return True
            else:
                for c in b_claves:
                    if c in self.claves[i]: return True
                return False
        return True

    def repe(self, item):
        while item in self.dic_items:
            item += ';'
        return item

    def clave_nuevo_nombre(self, nuevo_nombre=""):
        if not nuevo_nombre:
            self.dialogo('Nuevo nombre para '+self.clave_renombrar, 'renombrar_clave')
            return
        for i in range(len(self.registros)):
            campos = self.registros[i].split(';')
            for j in range(2,len(campos)):
                if campos[j] == self.clave_renombrar:
                    campos[j] = nuevo_nombre
                    self.registros[i] = ';'.join(campos)
                    break
            for j in range(len(self.claves[i])):
                if self.claves[i][j] == self.clave_renombrar:
                    self.claves[i][j] = nuevo_nombre
                    break
        self.clave.append(nuevo_nombre)
        self.clave.sort()
        self.lista_claves_cargadas = False
        self.grabar(modo='renom')

    def carga_listas(self):
        del self.items[:]
        del self.memos[:]
        del self.claves[:]
        del self.clave[:]
        for r in self.registros:
            campos = r.split(';')
            self.items.append(campos[0])
            self.memos.append(campos[1])
            self.claves.append(campos[2:])
            for c in campos[2:]:
                if c not in self.clave: self.clave.append(c)
        self.clave.sort()
        self.lista_claves_cargadas = False
        self.cargado = True

    def elige_claves(self, origen='', cuales='todas'):
        if self.eligiendo: return
        self.ids.lis_c_panta.adapter.selection_mode = 'multiple'
        if origen == 'buscar':
            self.ids.b_lista_c_izq.text = 'Menú'
            self.ids.b_lista_c_cen.text = 'Cancelar'
        else:
            self.ids.b_lista_c_izq.text = 'Cancelar'
            self.ids.b_lista_c_cen.text = 'Nueva'
        self.ids.b_lista_c_der.text = 'Aceptar'
        if not self.listando_claves:
            self.listando_claves = True
            self.titulo_lista = 'Claves'
            if not self.lista_claves_cargadas:
                del self.lista_claves[:]
                for c in self.clave: self.lista_claves.append(ClaveItem(text=c))
                self.lista_claves_cargadas = True
        self.marca_claves(origen)
        self.rellena_claves(cuales)
        #self.titulo_lista = 'Claves'
        self.eligiendo = True
        self.current = 'sc_lista_claves'
        if platform == 'android': android.hide_keyboard()

    def chequeos(self):
        reg = self.ids.i_item_alta.text + \
              self.ids.i_memo_alta.text + \
              self.ids.i_claves_alta.text
        if reg == "":
            self.aviso('Registro vacío')
            return False
        if reg.count(';'):
            self.aviso('No se puede usar ;')
            return False
        return True

    def eliminar_registros(self, confirmado=False, modo=''):
        if not confirmado:
            if modo == 'uno':
                self.confirmacion('¿Eliminar el registro?', 'elim_un_reg')
            else:
                self.confirmacion('¿Eliminar ' + str(len(self.dic_items)) + ' registros?', 'elim_n_regs')
            return
        if modo == 'uno':
            a_eliminar = [self.dic_items[self.ids.i_item.text]]
        else:
            a_eliminar = self.dic_items.values()
            a_eliminar.sort(reverse = True)
        for i in a_eliminar:
            self.registros.pop(i)
            self.items.pop(i)
            self.memos.pop(i)
            self.claves.pop(i)
        if self.graba_lista(self.abierto+TEMP, self.registros):
            rename(self.directorio+self.abierto+TEMP, self.directorio+self.abierto+FICH)
            self.num_lineas = str(int(self.num_lineas) - len(a_eliminar))
            self.aviso('Registro(s) eliminado(s)')
        else:
            self.abrir_archivo(self.abierto, incorporar=False)
        self.current = 'sc_menu_principal'

    def existe_fichero(self, nombre):
        if nombre+FICH in listdir(self.directorio):
            self.aviso('Ya existe ese fichero')
            return True
        return False

#    def exportar(self):
#        self.confirmacion('Opciones de exportación', 'exportar')

    def exportar_existente(self, nombre=''):
        if not nombre:
            self.selec_archivo('Archivo al que añadir')
            return
        try:
            F = open(self.directorio+nombre+FICH, 'a')
        except:
            self.aviso('No puedo abrir fichero')
            return
        regis = [self.registros[i] for i in self.dic_items.values()]
        try:
            for r in regis: F.write(r.encode('utf-8') + '\n')
        except:
            self.aviso('No puedo escribir en fichero')
            return
        finally:
            F.close()
        self.current = 'sc_menu_principal'
        self.aviso('Registros añadidos')

    def exportar_nuevo(self, nombre=''):
        if not nombre:
            self.dialogo('Nombre del fichero', 'fichero_exportar')
            return
        if self.existe_fichero(nombre): return
        regis = [self.registros[i] for i in self.dic_items.values()]
#        try:
            # F = open(self.directorio + nombre + FICH, 'w')
        # except:
            # self.aviso('No puedo crear fichero')
            # return
        # try:
            # for r in regis: F.write(r.encode('utf-8') + '\n')
        # except:
            # self.aviso('No puedo escribir fichero')
            # return
        # F.close()
        if self.graba_lista(nombre+FICH, regis):
            self.aviso('Exportados ' + str(len(regis)) + ' registros')

    def graba_lista(self, nombre, lista):
        try:
            F = open(self.directorio + nombre, 'w')
        except:
            self.aviso('No puedo crear fichero')
            return False
        try:
            for r in lista: F.write(r.encode('utf-8') + '\n')
        except:
            self.aviso('No puedo escribir fichero')
            remove(self.directorio + nombre)
            return False
        F.close()
        return True

    def fichero_nuevo(self, nombre=''):
        if not nombre:
            self.dialogo('Nombre del nuevo fichero', 'fichero_nuevo')
            return
        if self.existe_fichero(nombre): return
        try:
            open(self.directorio + nombre + FICH, 'w').close()
        except:
            self.aviso('No puedo crear fichero')
            return
        if self.abrir_archivo(nombre, incorporar=False):
            self.jstore.put("pim", ultimo=nombre, directorio=self.directorio)
            self.num_lineas = '0'
            self.current = 'sc_menu_principal'

    def grabar(self, modo=""):
        if modo=='modif' and not self.modificando:
            self.aviso('No está modificando')
            return
        if modo!='renom' and not self.chequeos(): return
        try: F = open(self.directorio + self.abierto + TEMP, 'w')
        except:
            self.aviso('No puedo crear fichero')
            return
        if modo != 'renom':
            reg = self.ids.i_item_alta.text.strip() + ';' + \
                  self.ids.i_memo_alta.text.rstrip().replace('\n',' ^ ') + ';' + \
                  self.ids.i_claves_alta.text.replace(',',';')
            if modo == 'nuevo':
                self.registros.append(reg)
                self.items.append(self.ids.i_item_alta.text)
                self.memos.append(self.ids.i_memo_alta.text.replace('\n',' ^ '))
                self.claves.append(self.ids.i_claves_alta.text.split(','))
            elif modo == 'modif':
                self.registros[self.reg] = reg
                self.items[self.reg] = self.ids.i_item_alta.text
                self.memos[self.reg] = self.ids.i_memo_alta.text.replace('\n',' ^ ')
                self.claves[self.reg] = self.ids.i_claves_alta.text.split(',')
        try:
            for r in self.registros: F.write(r.encode('utf-8') + '\n')
        except UnicodeEncodeError:
            try: remove(self.directorio + self.abierto+TEMP)
            except: pass
            self.aviso('Hay caracteres inválidos')
            return
        except:
            #self.aviso('No puedo escribir fichero')
            try: remove(self.directorio + self.abierto+TEMP)
            except: pass
            self.aviso(str(sys.exc_info()[0]))
            return
        F.close()
        rename(self.directorio + self.abierto+TEMP, self.directorio + self.abierto+FICH)
        if modo == 'nuevo': self.num_lineas = str(int(self.num_lineas) + 1)
        self.current = 'sc_menu_principal'
        if modo == 'renom': self.aviso('Clave renombrada')

    def importar(self, nombre):
        if self.abrir_archivo(nombre, incorporar=True):
            if self.graba_lista(self.abierto+TEMP, self.registros):
                rename(self.directorio+self.abierto+TEMP, self.directorio+self.abierto+FICH)
                self.aviso('Registros importados')
        else:
            self.abrir_archivo(self.abierto, incorporar=False)
        self.current = 'sc_menu_principal'

    def limpia_i_buscar_cadena(self):
        self.i_buscar_cadena.text = ""

    def limpia_b_buscar_claves(self):
        if self.b_buscar_claves.text != "":
            self.b_buscar_claves.text = ""
            for c in self.lista_claves: c.deselect()
            self.listando_claves = False

    def limpia_busqueda(self):
        self.limpia_i_buscar_cadena()
        self.limpia_b_buscar_claves()

    def lista_elegido(self, boton, texto):
        if self.titulo_lista.startswith('Registros encontrados'):
            self.reg = self.dic_items[texto]
            self.ids.i_item.text = self.items[self.reg]
            self.ids.i_memo.text = self.memos[self.reg].replace(' ^ ','\n')
            self.ids.i_claves.text = ','.join(self.claves[self.reg])
            self.ids.i_item.readonly = True
            self.ids.i_memo.readonly = True
            self.ids.i_claves.readonly = True
            self.current = 'sc_registro'
        elif self.titulo_lista == 'Claves':
            #self.claves_seleccionadas.append('kkk'); return
            #~ cla_selec = [c.text for c in self.ids.lis_panta.adapter.data if c.is_selected]
            if texto in self.claves_seleccionadas:
                self.claves_seleccionadas.remove(texto)
                for c in self.ids.lis_c_panta.adapter.data:
                    if c.text == texto: c.is_selected = False
            else:
                self.claves_seleccionadas.append(texto)
                for c in self.ids.lis_c_panta.adapter.data:
                    if c.text == texto: c.is_selected = True
            #~ cla_selec = [c.text for c in self.ids.lis_panta.adapter.data if c.is_selected]
        elif self.titulo_lista == 'Elegir archivo':
            if self.abrir_archivo(texto, incorporar=False):
#                self.jstore.put("pim", directorio='/mnt/sdcard/PIM/', ultimo=texto)
                self.jstore.put("pim", directorio=self.directorio, ultimo=texto)
                self.current = 'sc_menu_principal'
        elif self.titulo_lista == 'Archivo a importar':
            self.importar(texto)
        elif self.titulo_lista == 'Archivo a borrar':
            self.borrar_fich(confirmado=False, nombre=texto)
        elif self.titulo_lista == 'Clave a renombrar':
            self.clave_renombrar = texto
            self.clave_nuevo_nombre("")
        elif self.titulo_lista == 'Archivo al que añadir':
            self.exportar_existente(nombre=texto)


    def marca_claves(self, origen):
        if origen == 'buscar':
            self.claves_buscando = True
            if self.ids.b_buscar_claves.text: self.claves_seleccionadas = self.ids.b_buscar_claves.text.split(',')
            else: self.claves_seleccionadas = []
        else:
            self.claves_buscando = False
            if not self.clave_nueva:
                if self.ids.i_claves_alta.text: self.claves_seleccionadas = self.ids.i_claves_alta.text.split(',')
                else: self.claves_seleccionadas = []
            else:
                self.clave_nueva = False
        for cl in self.lista_claves:
            cl.is_selected = True if cl.text in self.claves_seleccionadas else False

    def limpia_claves_vacias(self):
        for i in range(len(self.registros)):
            if self.registros[i].count(';') > 2:
                self.registros[i] = self.registros[i].rstrip('; ')
                while self.registros[i].count(';') < 2:
                    self.registros[i] += ';'
        if self.graba_lista(self.abierto+TEMP, self.registros):
            rename(self.directorio+self.abierto+TEMP, self.directorio+self.abierto+FICH)
            self.current = 'sc_menu_principal'
            self.aviso('Claves limpiadas')
        self.cargado = False

    def modificar(self):
        self.ids.i_item_alta.text = self.ids.i_item.text
        self.ids.i_memo_alta.text = self.ids.i_memo.text
        self.ids.i_claves_alta.text = self.ids.i_claves.text
        self.modificando = True
        self.current = 'sc_alta'

    def orden_archivo(self, orden):
        self.registros.sort(reverse=(orden=='des'), key=lambda s: s.lower())
        if self.graba_lista(self.abierto+TEMP, self.registros):
            rename(self.directorio+self.abierto+TEMP, self.directorio+self.abierto+FICH)
            self.current = 'sc_menu_principal'
            self.aviso('Archivo ordenado')
            #self.cargado = False

    def orden_lista(self, orden):
        self.ids.lis_panta.adapter.data.sort()
        if orden == 'des': self.ids.lis_panta.adapter.data.reverse()

    def panta_buscar(self):
        if self.abierto:
            if not self.cargado: self.carga_listas()
            self.ids.titulo_sc_buscar.text = 'Buscando en ' + self.titulo_fichero
            self.current = 'sc_buscar'
            self.ids.i_buscar_cadena.focus = True

    def rellena(self, tipo=""):
        #~ self.lis_panta.item_strings = ['wefrewr', 'klsjf lkj f']
        #~ self.lis_panta.adapter.data.clear()
        #self.titulo_lista = 'Ficheros disponibles'
        del self.ids.lis_panta.adapter.data[:]
        if tipo == "ficheros":
            #~ self.ids.lis_panta.adapter.data = self.lista
            self.ids.lis_panta.adapter.cls = BotonDeLista
        else:
            self.ids.lis_panta.adapter.cls = LabelDeLista
        self.ids.lis_panta.adapter.data.extend(self.lista)
        self.ids.lis_panta._trigger_reset_populate()

    def rellena_claves(self, cuales):
        del self.ids.lis_c_panta.adapter.data[:]
        if cuales == 'todas':
            self.ids.lis_c_panta.adapter.data.extend(self.lista_claves)
        elif cuales == 'marcadas':
            self.ids.lis_c_panta.adapter.data.extend(c for c in self.lista_claves if c.text in self.claves_seleccionadas)
        else:
            letra = cuales.lower()
            self.ids.lis_c_panta.adapter.data.extend(c for c in self.lista_claves if c.text.lower()>=letra)
        self.ids.lis_c_panta._trigger_reset_populate()

    def args_converter(self, index, data_item):
        #~ texto = data_item
        #~ return {'texto': texto}
        return {'text': data_item}

    def args_converter_claves(self, index, data_item):
        #~ texto = data_item.text
        #~ return {'texto': texto}
        return {'text': data_item.text}

    def renombrar_clave(self):
        if not self.cargado: self.carga_listas()
        self.clave_renombrar = ""
        #self.ids.lis_c_panta.adapter = ListAdapter(data=[], cls=BotonDeLista, args_converter=self.args_converter_claves)
        self.ids.lis_c_panta.adapter.selection_mode = 'single'
        self.titulo_lista = 'Clave a renombrar'
        self.ids.b_lista_c_izq.text = 'Menu'
        self.ids.b_lista_c_cen.text = ''
        self.ids.b_lista_c_der.text = ''
        self.ids.b_lista_c_over.text = 'Cancelar'
        if not self.lista_claves_cargadas:
            del self.lista_claves[:]
            for c in self.clave: self.lista_claves.append(ClaveItem(text=c))
            self.lista_claves_cargadas = True
        self.rellena_claves('todas')
        self.current = 'sc_lista_claves'

    def traduce(self, s):
        s = s.encode('utf-8')
        s = s.replace('á','a').replace('é','e').replace('í','i')\
             .replace('ó','o').replace('ú','u').replace('ñ','n')\
             .replace('ç','c')
        return s.decode('utf-8')
from secp256k1 import PrivateKey, PublicKey
import os

demo_user_names = ('Alice', 'Bob', 'Charlie', 'Mark', 'King', 'Wu', 'Paige')
Builder.load_file('main.kv')  # load *.kv file
default_path = './demo_users.json'
message_path = './messages.json'
block_height = 0
message_hash = set()
contact_map = {}

# read block info
try:
    init_store = JsonStore(message_path)
    if not init_store.exists('block'):  # initialize block info
        init_store.put('block', height=0)
    else:
        block_height = init_store.get('block')['height']
        for i in range(0, block_height):
            msg_hash = init_store[str(i)]['hash']
            message_hash.add(msg_hash)
    # print(message_hash)
except Exception as e:
    print(str(e))


class DemoUserSelScreen(Screen):
    """select demo user screen"""
    pass

Beispiel #52
0
class Controller(EventDispatcher):
    """
    Controls the playing of audio and coordinates the updating of the playlist
    and screen displays
    """
    volume = NumericProperty(1.0)
    advance = True
    # This flag indicates whether to advance to the next track
    # once the currently playing one had ended

    sm = None  # THe ScreenManager
    pos = 0

    def __init__(self, **kwargs):
        """ Initialize the screens and the screen manager """
        self._store = JsonStore(join(self._get_settings_folder(),
                                     "zenplayer.json"))
        self.playlist = PlayList(self._store)

        self.sm = ScreenManager()
        self.playing = PlayingScreen(self, name="main")
        self.sm.add_widget(self.playing)
        self.sm.current = "main"

        if platform not in ['ios', 'android']:
            self.kb_listener = ZenKeyboardListener(self.on_key_down,
                                                   self.playing)
        Sound.add_state_callback(self.playing.on_sound_state)
        Sound.add_state_callback(self._on_sound_state)

        super(Controller, self).__init__(**kwargs)
        if self._store.exists('state'):
            state = self._store.get("state")
            if "volume" in state.keys():
                self.volume = state["volume"]

    @staticmethod
    def _get_settings_folder():
        """ Return the folder when the setting file is stored. """
        path = expanduser("~/.zencode")
        if not exists(path):
            mkdir(path)
        return path

    def _on_sound_state(self, state):
        """ The sound state has changed. If the track played to the end,
        move to the next track."""
        if state == "finished" and self.advance:
            self.play_next()

    def get_current_art(self):
        return self.playlist.get_current_art()

    def get_current_info(self):
        return self.playlist.get_current_info()

    def get_current_file(self):
        return self.playlist.get_current_file()

    @staticmethod
    def get_pos_length():
        return Sound.get_pos_length()

    def on_key_down(self, keyboard, keycode, text, modifiers):
        """ React to the keypress event """
        key_name = keycode[1]
        if key_name == "up" or text == "+":
            self.volume += 0.025
        elif key_name == "down" or text == "-":
            self.volume -= 0.025
        elif key_name == "x":
            self.play_pause()
        elif key_name == "z":
            self.play_previous()
        elif key_name == "v":
            self.stop()
        elif key_name == "b":
            self.play_next()
        elif key_name == "a":
            self.show_filebrowser()
        elif key_name == "p":
            self.show_playlist()
        elif key_name == "s":
            self.show_main()

        return True

    def on_volume(self, widget, value):
        """ Set the volume of the currently playing sound """
        if 0.0 > value:
            self.volume = 0.0
        elif value > 1.0:
            self.volume = 1.0
        else:
            Sound.set_volume(value)
            self.playing.volume_slider.value = value

    def play_index(self, index):
        """
        Play the track with the specified playlist index
        """
        Sound.stop()
        self.playlist.current = index
        self.play_pause()

    def play_pause(self):
        """ Play or pause the currently playing track """
        self.advance = True
        if Sound.state == "playing":
            self.pos, x = Sound.get_pos_length()
            Sound.stop()
        else:
            audio_file = self.get_current_file()
            if audio_file:
                Sound.play(audio_file, self.volume)
                if self.pos > 0:
                    def set_pos(dt):
                        Sound.seek(self.pos)
                        self.pos = 0
                    Clock.schedule_once(set_pos, 0.1)

    def play_next(self):
        """ Play the next track in the playlist. """

        Sound.stop()
        self.playlist.move_next()
        self.play_pause()

    def play_previous(self):
        """ Play the previous track in the playlist. """
        Sound.stop()
        self.playlist.move_previous()
        self.play_pause()

    @staticmethod
    def set_position(value):
        """ Set the playing position to the specified value. """
        Sound.set_position(value)

    def save(self):
        """ Save the state of the the playlist and volume. """
        self.playlist.save(self._store)
        self._store.put("state", volume=self.volume)
        if "filebrowser" in self.sm.screen_names:
            self.sm.get_screen("filebrowser").save(self._store)

    def show_filebrowser(self):
        """ Switch to the file browser screen """
        if "filebrowser" not in self.sm.screen_names:
            self.sm.add_widget(ZenFileBrowser(self,
                                              self.playlist,
                                              self._store,
                                              name="filebrowser"))
        self.sm.current = "filebrowser"

    def show_playlist(self):
        """ Switch to the playlist screen """
        if "playlist" not in self.sm.screen_names:
            self.sm.add_widget(PlayListScreen(self.sm,
                                              self,
                                              self.playlist,
                                              name="playlist"))
        self.sm.current = "playlist"

    def show_main(self):
        """ Switch to the main playing screen"""
        self.sm.current = "main"

    def stop(self):
        """ Stop any playing audio """
        self.advance = False
        Sound.stop()
Beispiel #53
0
class WeatherRoot(BoxLayout):

    current_weather = ObjectProperty()
    locations = ObjectProperty()
    forecast = ObjectProperty()

    def __init__(self, **kwargs):
        super(WeatherRoot, self).__init__(**kwargs)
        self.store = JsonStore("weather_store.json")
        if self.store.exists("locations"):
            current_location = self.store.get("locations")["current_location"]
            self.show_current_weather(current_location)

    def show_current_weather(self, location=None):
        self.clear_widgets()

        if self.current_weather is None:
            self.current_weather = CurrentWeather()

        if self.locations is None:
            self.locations = Factory.Locations()
            if self.store.exists("locations"):
                locations = self.store.get("locations")["locations"]
                self.locations.locations_list.adapter.data.extend(locations)

        if location is not None:
            self.current_weather.location = location
            if location not in self.locations.locations_list.adapter.data:
                self.locations.locations_list.adapter.data.append(location)
                self.locations.locations_list._trigger_reset_populate()
                self.store.put("locations",
                               locations=list(
                                   self.locations.locations_list.adapter.data),
                               current_location=location)

        self.current_weather.update_weather()
        self.add_widget(self.current_weather)

    def show_add_location_form(self):
        self.clear_widgets()
        self.add_widget(AddLocationForm())

    def show_locations(self):
        self.clear_widgets()
        self.add_widget(self.locations)

    def show_cover_page(self):
        self.clear_widgets()
        self.add_widget(CoverPage())

    def show_forecast(self, location=None):
        self.clear_widgets()

        if self.forecast is None:
            self.forecast = Forecast()

        if location is not None:
            self.forecast.location = location

        self.forecast.update_weather()
        self.add_widget(self.forecast)
	def saveobjectsize(self):
		store = JsonStore('Saved_variables.json')
		store.put('ballsize',ballsize = self.objectsize)
Beispiel #55
0
class FindBWidget(BoxLayout):
    level=NumericProperty(1)
    bfound = NumericProperty(0)
    bnumber = NumericProperty(0)
    
    def __init__(self,**kwargs):
        super(FindBWidget,self).__init__(**kwargs)
        self.BBoxList=[]
        self.store = JsonStore("findb.json")
        self.gridSize_height = 0
        self.gridSize_width = 0
        self.bnumber = 0
        self.badded = 0
        self.bfound = 0
        self.mute=True
        self.gameover = False
        self.custimize = False
        self.custimize_height = 0
        self.custimize_width = 0
        self.custimize_brate = 0.2
        
        self.sounds = {'bomb':SoundLoader.load('bomb.wav'),
                       'state':SoundLoader.load('state.wav'),
                       'upgrade':SoundLoader.load('upgrade.mp3')}
        
        self.start_clock = clock()
        self.config = None
                
    def on_bfound(self,instance,value):
        self.status_bar.label_left_bomb.text = '{}'.format(self.bnumber - self.bfound)
        self.CheckSucceed()

    def on_bnumber(self,instance,value):
        self.status_bar.label_left_bomb.text = '{}'.format(self.bnumber - self.bfound)

    def Restart(self):
        self.custimize,self.custimize_height,self.custimize_width,self.custimize_brate = self.get_customize_info()
        self.level,self.levels_info = self.get_level_info()
        self.mute = self.get_mute_info()
        
        self.BBoxList = []
                
        if self.custimize == True:
            self.status_bar.label_level.text = 'L:C'
            self.gridSize_height = self.custimize_height
            self.gridSize_width = self.custimize_width
            
            if self.gridSize_height < 5:
                self.gridSize_height = 5
            if self.gridSize_width < 5:
                self.gridSize_width = 5
            if self.gridSize_height > 50:
                self.gridSize_height = 50
            if self.gridSize_width > 50:
                self.gridSize_width = 50
        else:
            self.status_bar.label_level.text = 'L:{}'.format(self.level)
            self.gridSize_width = self.level + Rows_For_First_Level
            self.gridSize_height = self.level + Rows_For_First_Level            
        
        self.bnumber = 0
        self.badded = 0
        self.bfound = 0
        self.start_clock = clock()
        self.gameover = False
        self.play_area.clear_widgets()
        self.play_area.cols = self.gridSize_width
        self.play_area.rows = self.gridSize_height
        
        for i in range(0,self.gridSize_height):
            for j in range(0,self.gridSize_width):
                b = BBox(root=self)
                b.row=i
                b.col=j
                self.BBoxList.append(b)
                self.play_area.add_widget(b)
        
        self._calculate_bombs()
        
        self.status_bar.toggle_mark.disable = False
        self.status_bar.toggle_mark.state = "normal"
        self.status_bar.button_reset.image.source='smile.png'

    def _calculate_bombs(self):
        if self.custimize:
            self.brate = self.custimize_brate/100.0
            if self.brate < 0.05:
                self.brate = 0.05
            if self.brate > 0.8:
                self.brate = 0.8
        elif self.level < 6:
            self.brate = 0.11
        elif self.level < 11:
            self.brate = 0.13
        elif self.level < 20:
            self.brate = 0.15
        elif self.level < 30:
            self.brate = 0.18
        else:
            self.brate = 0.2
            
        self.bnumber = int(self.brate * self.gridSize_width * self.gridSize_height)
        
        self.badded = 0
        while True:
            if self._add_bomb():
                self.badded += 1
                
            if self.badded >= self.bnumber:
                break

    def _add_bomb(self):
        if len(self.BBoxList) <=0:
            return
        
        i = Random().randint(0,len(self.BBoxList) - 1)
        
        if self.BBoxList[i].isBomb:
            return False
        else:
            self.BBoxList[i].isBomb = True
            #set bomb number of the around boxes
            row = self.BBoxList[i].row
            col = self.BBoxList[i].col            

            self._add_bomb_number(row - 1,col - 1)
            self._add_bomb_number(row - 1,col)
            self._add_bomb_number(row - 1,col + 1)                
            self._add_bomb_number(row,col - 1)
            self._add_bomb_number(row,col + 1)
            self._add_bomb_number(row + 1,col - 1)
            self._add_bomb_number(row + 1,col)
            self._add_bomb_number(row + 1,col + 1)
                    
        return True
    def _add_bomb_number(self,row,col):
        if row < 0 or row >= self.gridSize_width or col < 0 or col >= self.gridSize_height:
            return
        
        index = row*self.gridSize_width + col
        if index < 0 or index >= len(self.BBoxList):
            return
        
        self.BBoxList[index].BNumber += 1
    
        
    def Clear(self,row,col):
        if row < 0 or row >= self.gridSize_width or col < 0 or col >= self.gridSize_height:
            return
        
        index = row*self.gridSize_width + col
        if index < 0 or index >= len(self.BBoxList):
            return
        
        self.BBoxList[index].MarkNumberOrEmpty()
    
    def ShowAll(self):
        self.status_bar.toggle_mark.state='normal'
        for i in range(0,len(self.BBoxList)):
            if self.BBoxList[i].isBomb:
               self.BBoxList[i].bbutton.MarkB()
            else:
                self.BBoxList[i].Clear()

    def CheckSucceed(self):
        if self.bfound > 0 and self.bfound == self.bnumber:
            for i in range(0,len(self.BBoxList)):
                if self.BBoxList[i].state == 0:
                    return False

            #upgrade level  
            if self.mute == False:
                self.sounds['upgrade'].play()
            
            
            if self.custimize == False:
                duration = round((clock() - self.start_clock),2)                
            
                if self.levels_info.has_key(self.level) and self.levels_info[self.level] > 0:
                    if self.levels_info[self.level] > duration:
                        self.levels_info[self.level] = duration
                else:
                    self.levels_info[self.level] = duration
                    
                if self.level < Max_Level:
                    self.level += 1
                    
                self.store_user_data(self.level,self.levels_info)

            self.Restart()
            
            return True
        else:
            return False
        
    def get_level_info(self):
        if self.store.exists("UserData") == False:
            self.store.put("UserData",CurrentLevel=1,Levels={})
        
        return self.store.get("UserData")["CurrentLevel"],self.store.get("UserData")["Levels"]
    def get_mute_info(self):
        return self.config.get('Sounds','Mute') == '1'
    
    def get_customize_info(self):
       return self.config.get('Customization','Enable') == '1',self.config.getint('Customization','C_Height'),self.config.getint('Customization','C_Width'),self.config.getint('Customization','Rate')

    def store_user_data(self,currentLevel,levels):
        self.store.put("UserData",CurrentLevel=currentLevel,Levels=levels)
        
    def GameOver(self):
        self.status_bar.toggle_mark.disable = True
        self.status_bar.button_reset.image.source='gameover.png'
        self.gameover = True
Beispiel #56
0
from kivy.storage.jsonstore import JsonStore


def show_me(**kwargs):
    print(kwargs)
    for k, v in kwargs.items():
        print(f'{k} = {v}')


d1 = {'dog': 1, 'cat': 2, 'mouse': 3}

print('\nPass a dictionary as keywords')
show_me(**d1)

print('\nPass Keywords')
show_me(box=4, fox=5, eggs=6)

store = JsonStore('test_1.json')
store.put('color', red=1, white=2, blue=3)
store.put('critters', **d1)
print(f"\nstore.get('critters') = {store.get('critters')}")
Beispiel #57
0
 def on_leave(self):
     """ The filebrowser screen is being closed """
     if len(self.filechooser.selection) > 0:
         store = JsonStore("zenplayer.json")
         store.put("filebrowser", path=self.filechooser.selection[0])
Beispiel #58
0
class LoginScreen(Screen):
    def on_enter(self):
        self.storage = JsonStore("storage.json")

        if self.storage.exists("user"):
            user = self.storage.get("user")

            if user["remember"]:
                query = gql("""
                    mutation VerifyToken($token: String!) {
                        verifyToken(input: {
                                token: $token
                            }) {
                            payload
                        }
                    }
                """)

                result = sync_request(query, token=user["authToken"])

                if result["verifyToken"]["payload"] is not None:
                    Clock.schedule_once(self.to_main_screen)

    def login(self):
        self.ids.email_input, email_valid = validate_input(
            self.ids.email_input, not self.ids.email_input,
            "Este campo é obrigatório")

        self.ids.email_input, password_valid = validate_input(
            self.ids.email_input, not self.ids.email_input,
            "Este campo é obrigatório")

        if email_valid and password_valid:

            query = gql("""
                mutation Login($email: String!, $password: String!) {
                    tokenAuth(
                        input: {
                            email: $email,
                            password: $password
                        }
                    ) {
                        success,
                        errors,
                        token,
                        user {
                            id,
                            firstName,
                            lastName
                        }
                    }
                }
            """)

            email = self.ids.email_input.text

            result = sync_request(query,
                                  email=email,
                                  password=self.ids.password_input.text)

            if result["tokenAuth"]["success"]:
                user = result["tokenAuth"]["user"]
                user_name = f"{user['firstName']} {user['lastName']}"

                self.storage.put("user",
                                 id=user["id"],
                                 name=user_name,
                                 email=email,
                                 authToken=result["tokenAuth"]["token"],
                                 remember=self.ids.remember_input.active)

                self.manager.current = "main"
            else:
                errors = result["tokenAuth"]["errors"]

                for error_field in errors.keys():
                    if error_field == "nonFieldErrors":
                        self.add_widget(
                            MDLabel(text=errors[error_field]["message"],
                                    theme_text_color="Error",
                                    font_style="H6"))
                    else:
                        self.ids[
                            f"{error_field}_input"], input_valid = validate_input(
                                self.ids[f"{error_field}_input"],
                                True,
                                errors[error_field][0]["message"],
                            )

    def to_main_screen(self, event):
        self.manager.current = "main"
Beispiel #59
0
def on_success(obj, result):
    clases = result.get("get")

    db = JsonStore("../db/clases.json")
    lista = []
    for clase in clases.get("clases"):
        row_clase = {
            'text': clase["nombre"],
            'bgColor': clase["color"],
            'tipo': 'clase',
            "preguntas": []
        }
        if "precio" in clase:
            row_clase["precio"] = clase["precio"]
        if "promocion" in clase:
            row_clase["promocion"] = clase["promocion"]
        lista.append(row_clase)

        row_clase['productos'] = unicode(clase["nombre"])
        db_pro = JsonStore(u"../db/productos/{0}.json".format(
            unicode(clase["nombre"])))
        lista_productos = []
        for pro in clase["productos"]:
            row = {
                'text': pro["nombre"],
                'bgColor': pro["color"],
                'preguntas': [],
                'modificadores': [],
                'tipo': clase["nombre"].lower()
            }
            if "precio" in pro:
                row["precio"] = pro["precio"]
            if "promocion" in clase:
                row["promocion"] = clase["promocion"]

            if len(pro['ingredientes']) > 0:
                row["ingredientes"] = pro['nombre']
                db_ing = JsonStore(u"../db/ingredientes/{0}.json".format(
                    unicode(pro['nombre'])))
                lista_ing = []
                for ing in pro["ingredientes"]:
                    row_ing = {
                        'text': ing["nombre"],
                        'bgColor': ing["color"],
                        "precio": ing["precio"] if "precio" in ing else 0
                    }
                    lista_ing.append(row_ing)
                db_ing.put("selectable", estado=True)
                db_ing.put("db", lista=lista_ing)

            lista_productos.append(row)

        db_pro.put("db", lista=lista_productos)

        row_clase["preguntas"] = []
        for clase_preg in clase["clasespreguntas"]:
            nombre = clase_preg["nombre"]
            row_clase["preguntas"].append(nombre)
            db_pre = JsonStore(u"../db/preguntas/{0}.json".format(
                unicode(nombre)))
            lista_preg = []
            for preg in clase_preg["preguntas"]:
                row_ing = {
                    'text': preg["nombre"],
                    'bgColor': preg["color"],
                }
                if "precio" in preg:
                    row_ing["precio"] = preg["precio"]

                lista_preg.append(row_ing)

            db_pre.put("db", lista=lista_preg)

    db.put('db', lista=lista)
Beispiel #60
0
class MyScreenManager(ScreenManager):
    #ultimo = ""
    directorio = ''
    abierto = ""
    cargado = False
    modificando = False     # alta o modificando
    reg = 0
    claves_buscando = False # para saber quien listó las claves
    dic_items = {}          # {item: 'indice registro'}
    lista = []
    lista_claves = []
    listando_claves = False
    lista_claves_cargadas = False
    claves_seleccionadas = []
    eligiendo = False
    clave_nueva = False
    clave_renombrar = ""
    #pulsacion = False
    jstore = ""
    registros = [] # las lineas del fichero
    items = []
    memos = []
    claves = []  # lista de claves de cada registro [[cla1,cla2],[],...]
    #indice = []
    clave = []   # claves existentes
    num_lineas = StringProperty()
    #jstore = JsonStore("pim_store.json")
    #i_item = ObjectProperty()
    i_buscar_item = ObjectProperty()
    b_buscar_claves = ObjectProperty()
    #lis_panta = ObjectProperty()
    titulo_lista = StringProperty()
    titulo_fichero = StringProperty()
    panta = StringProperty()
    smBotonDeLista = BotonDeLista
    smBotonDeVocales = BotonDeVocales
    mayusculas = uppercase

    def __init__(self, **kwargs):
        super(MyScreenManager, self).__init__(**kwargs)
        self.current = 'sc_menu_principal'
        if platform == 'android': android.hide_keyboard()
        self.jstore = JsonStore("pim_store.json")
        try:
            ultimo = self.jstore.get("pim")['ultimo']
            self.directorio = self.jstore.get("pim")['directorio']
        except:
            return
        if not self.abrir_archivo(ultimo, incorporar=False, aviso=False):
            self.selec_archivo('Elegir archivo')
        log('año')
        log(u'año')

    def abrir_archivo(self, fich, incorporar, aviso=True):
        try:
            F = open(self.directorio + fich + FICH)
        except:
            if aviso: self.aviso('No puedo abrir ' + fich)
            return False
        if not incorporar: del self.registros[:]
        num_lineas = 0
        try:
            r = F.readline()
            while r:
                if len(r) > 2:
                    self.registros.append(r[:-1].decode('utf-8'))
                    #self.registros.append(r[:-1])
                    num_lineas += 1
                r = F.readline()
        except:
            self.aviso('No puedo leer ' + fich + ': ' + str(sys.exc_info()[0]))
            return False
        if not incorporar:
            self.abierto = fich
            self.titulo_fichero = fich
            self.num_lineas = str(num_lineas) if num_lineas else '0'
        else:
            self.num_lineas = str(int(self.num_lineas) + num_lineas)
        self.cargado = False
        return True

    def selec_archivo(self, opcion):
        #self.lista = [f[:-8] for f in listdir(getcwd()) if f[-8:]=='-PIM.csv']
        print '--------------------', self.directorio
        self.lista = [f[:-8] for f in listdir(self.directorio) if f[-8:]=='-PIM.csv']
        self.lista.sort()
        self.ids.lis_panta.adapter = ListAdapter(data=[], cls=BotonDeLista, args_converter=self.args_converter, selection_mode='single')
        self.listando_claves = False
        self.rellena("ficheros")
        self.titulo_lista = opcion
        self.ids.b_lista_izq.text = 'Menu'
        self.ids.b_lista_cen.text = ''
        self.ids.b_lista_der.text = ''
        self.ids.b_lista_over.text = 'Cancelar'
        self.current = 'sc_lista'

    def alta(self):
        if not self.cargado: self.carga_listas()
        self.ids.i_item_alta.text = ""
        self.ids.i_memo_alta.text = ""
        self.ids.i_claves_alta.text = ""
        self.modificando = False
        self.ids.i_item_alta.focus = True
        self.current = 'sc_alta'

    #def alta_clave(self, popup, cla):
        #if not cla: return
        #self.aviso(cla)
        #self.clave.append(cla)
        #self.clave.sort()
        #self.ids.i_claves_alta.text += ','+cla
        #popup.dismiss()
        #self.elige_claves('registro')

    def aviso(self, txt):
        the_content = Label(text = txt)
        the_content.color = (1,1,1,1)
        popup = Popup(title='PIM',
            content=the_content, size_hint_y=.25, title_align='center')
            #content = the_content, size_hint=(None, None), size=(350, 150))
        popup.open()

    def confirmacion(self, txt="", tema=""):
        def elim_1_reg(self):
            popup.dismiss()
            mapp.root.eliminar_registros(confirmado=True, modo='uno')
        def elim_n_reg(self):
            popup.dismiss()
            mapp.root.eliminar_registros(confirmado=True, modo='varios')
        def borr_fich(self):
            popup.dismiss()
            mapp.root.borrar_fich(confirmado=True, nombre=tema)
        def expor_exis(self):
            popup.dismiss()
            mapp.root.exportar_existente()
        def expor_nue(self):
            popup.dismiss()
            mapp.root.exportar_nuevo()
        def cancelar(self):
            popup.dismiss()
        cuerpo = Confirmacion(txt)
        cuerpo.color = (1,0,0,1)
        if tema == 'exportar':
            cuerpo.ids.b_aceptar.text = 'Añadir a existente'
            cuerpo.ids.b_cancelar.text = 'Archivo nuevo'
            cuerpo.ids.b_cancelar.bind(on_release=expor_nue)
        else:
            cuerpo.ids.b_aceptar.text = 'Aceptar'
            cuerpo.ids.b_cancelar.text = 'Cancelar'
            cuerpo.ids.b_cancelar.bind(on_release=cancelar)
        popup = Popup(title='CONFIRMACION',
            content=cuerpo, size_hint_y=.25, title_align='center',
            title_color=[1,0,0,1], auto_dismiss=False)
        if tema == 'elim_un_reg':
            cuerpo.ids.b_aceptar.bind(on_release=elim_1_reg)
        if tema == 'elim_n_regs':
            cuerpo.ids.b_aceptar.bind(on_release=elim_n_reg)
        if tema == 'exportar':
            cuerpo.ids.b_aceptar.bind(on_release=expor_exis)
        if tema.startswith('fichero-'):
            cuerpo.ids.b_aceptar.bind(on_release=borr_fich)
        popup.open()

    def dialogo(self, txt='', tema=''):
        def alta_clave(self):
            nueva = the_content.ids.i_dialog.text.strip()
            if not nueva: return
            mapp.root.clave.append(nueva)
            mapp.root.clave.sort()
            mapp.root.lista_claves.append(ClaveItem(text=nueva, is_selected=True))
            mapp.root.claves_seleccionadas.append(nueva)
            if mapp.root.ids.i_claves_alta.text:
                mapp.root.ids.i_claves_alta.text += ',' + nueva
            else:
                mapp.root.ids.i_claves_alta.text = nueva
            popup.dismiss()
            mapp.root.clave_nueva = True
            mapp.root.elige_claves('registro')
        def nuevo_fichero(self):
            popup.dismiss()
            mapp.root.fichero_nuevo(the_content.ids.i_dialog.text.strip())
        def exportar_fichero(self):
            popup.dismiss()
            mapp.root.exportar_nuevo(the_content.ids.i_dialog.text.strip())
        def renombre_clave(self):
            popup.dismiss()
            mapp.root.clave_nuevo_nombre(the_content.ids.i_dialog.text.strip())
        the_content = Dialogo(txt)
        the_content.color = (1,1,1,1)
        popup = Popup(title=txt,
            content=the_content, size_hint_y=.25, title_align='center', auto_dismiss=False)
        the_content.ids.b_cancelar.bind(on_release=popup.dismiss)
        if tema == 'clave':
            #~ the_content.ids.b_aceptar.bind(on_release=self.alta_clave(popup, the_content.ids.i_dialog.text))
            the_content.ids.b_aceptar.bind(on_release=alta_clave)
        elif tema == 'fichero_nuevo':
            the_content.ids.b_aceptar.bind(on_release=nuevo_fichero)
        elif tema == 'renombrar_clave':
            the_content.ids.b_aceptar.bind(on_release=renombre_clave)
        elif tema == 'fichero_exportar':
            the_content.ids.b_aceptar.bind(on_release=exportar_fichero)
        popup.open()

    def borrar_fich(self, confirmado, nombre):
        if not confirmado:
            self.confirmacion(u'¿Borrar el archivo ' + nombre + '?', 'fichero-'+nombre)
            return
        nombre = nombre[8:]
        try:
            remove(self.directorio + nombre + FICH)
            self.current = 'sc_menu_principal'
            self.aviso('Archivo borrado')
        except:
            self.aviso('Error al borrar archivo')

    def boton_lista_izq(self, texto):
        if self.titulo_lista == 'Claves':
            self.eligiendo = False
            if texto == 'Cancelar':
                self.current = 'sc_alta'
                return
        self.current = 'sc_menu_principal'
        #if texto == 'Menu': self.current = 'sc_menu_principal'

    def boton_lista_cen(self, texto):
        if self.titulo_lista.startswith('Registros encontrados'):
            #self.exportar()
            self.confirmacion('Opciones de exportación', 'exportar')
        elif self.titulo_lista == 'Claves':
            self.eligiendo = False
            if texto == 'Nueva':
                self.dialogo('Introduzca nueva clave', 'clave')
            else:
                self.current = 'sc_buscar'

    def boton_lista_der(self, texto):
        #~ self.ids.lis_panta._trigger_reset_populate()
        if self.titulo_lista.startswith('Registros encontrados'):
            self.current = 'sc_buscar'
        elif self.titulo_lista == 'Claves':
            self.eligiendo = False
            #~ cla_selec = [c.text for c in self.ids.lis_panta.adapter.data if c.is_selected]
            self.claves_seleccionadas.sort()
            if self.claves_buscando:
                self.ids.b_buscar_claves.text = ",".join(self.claves_seleccionadas)
                self.current = 'sc_buscar'
            else:
                self.ids.i_claves_alta.text = ",".join(self.claves_seleccionadas)
                self.current = 'sc_alta'

    def boton_lista_over(self, texto):
        if texto == 'Eliminar':
            self.eliminar_registros(confirmado=False, modo='varios')
        elif texto == 'Cancelar':
            self.current = 'sc_menu_principal'

    def busca(self):
        del self.lista[:]
        #self.dic_items = {}
        self.dic_items.clear()
        cad = self.i_buscar_cadena.text.lower()
        if self.ids.sw_ignora.active:
            cad = self.traduce(cad)
            if self.ids.cb_y.active:
                for i in range(len(self.items)):
                    if self.cadena_en_texto_ignora(i,cad) and self.clave_en_claves(i):
                        self.dic_items[self.repe(self.items[i])] = i
            else:
                for i in range(len(self.items)):
                    if self.cadena_en_texto_ignora(i,cad) or self.clave_en_claves(i):
                        self.dic_items[self.repe(self.items[i])] = i
        else:
            if self.ids.cb_y.active:
                for i in range(len(self.items)):
                    if self.cadena_en_texto(i,cad) and self.clave_en_claves(i):
                        self.dic_items[self.repe(self.items[i])] = i
            else:
                for i in range(len(self.items)):
                    if self.cadena_en_texto(i,cad) or self.clave_en_claves(i):
                        self.dic_items[self.repe(self.items[i])] = i
        self.lista = sorted(self.dic_items.keys(), reverse = True)
        #self.lista.sort()
        self.ids.lis_panta.adapter = ListAdapter(data=[], cls=BotonDeLista, args_converter=self.args_converter, selection_mode='single')
        self.titulo_lista = 'Registros encontrados: ' + str(len(self.lista))
        self.ids.b_lista_izq.text = 'Menu'
        self.ids.b_lista_cen.text = 'Exportar'
        self.ids.b_lista_der.text = 'Buscar'
        self.ids.b_lista_over.text = 'Eliminar'
        self.listando_claves = False
        self.rellena("items")
        self.current = 'sc_lista'

    def cadena_en_texto(self, i, cad):
        if cad:
            if self.ids.sw_busca.active:
                if not (self.items[i].lower().count(cad) or self.memos[i].lower().count(cad)):
                    return False
            else:
                if not self.items[i].lower().count(cad):
                    return False
        return True

    def cadena_en_texto_ignora(self, i, cad):
        if cad:
            if self.ids.sw_busca.active:
                if not (self.traduce(self.items[i].lower()).count(cad) or self.traduce(self.memos[i].lower()).count(cad)):
                    return False
            else:
                if not self.traduce(self.items[i].lower()).count(cad):
                    return False
        return True

    def clave_en_claves(self, i):
        #if self.b_buscar_claves.text != '<claves>':
        if self.b_buscar_claves.text != '':
            b_claves = self.b_buscar_claves.text.split(',')
            Y_claves = True
            if Y_claves:
                for c in b_claves:
                    if c not in self.claves[i]: return False
                return True
            else:
                for c in b_claves:
                    if c in self.claves[i]: return True
                return False
        return True

    def repe(self, item):
        while item in self.dic_items:
            item += SEP
        return item

    def clave_nuevo_nombre(self, nuevo_nombre=""):
        if not nuevo_nombre:
            self.dialogo('Nuevo nombre para '+self.clave_renombrar, 'renombrar_clave')
            return
        for i in range(len(self.registros)):
            campos = self.registros[i].split(SEP)
            for j in range(2,len(campos)):
                if campos[j] == self.clave_renombrar:
                    campos[j] = nuevo_nombre
                    self.registros[i] = SEP.join(campos)
                    break
            for j in range(len(self.claves[i])):
                if self.claves[i][j] == self.clave_renombrar:
                    self.claves[i][j] = nuevo_nombre
                    break
        self.clave.append(nuevo_nombre)
        self.clave.sort()
        self.lista_claves_cargadas = False
        self.grabar(modo='renom')

    def carga_listas(self):
        del self.items[:]
        del self.memos[:]
        del self.claves[:]
        del self.clave[:]
        for r in self.registros:
            campos = r.split(SEP)
            self.items.append(campos[0])
            self.memos.append(campos[1])
            self.claves.append(campos[2:])
            for c in campos[2:]:
                if c not in self.clave: self.clave.append(c)
        self.clave.sort()
        self.lista_claves_cargadas = False
        self.cargado = True

    def elige_claves(self, origen='', cuales='todas'):
        if self.eligiendo: return
        self.ids.lis_c_panta.adapter.selection_mode = 'multiple'
        if origen == 'buscar':
            self.ids.b_lista_c_izq.text = 'Menú'
            self.ids.b_lista_c_cen.text = 'Cancelar'
        else:
            self.ids.b_lista_c_izq.text = 'Cancelar'
            self.ids.b_lista_c_cen.text = 'Nueva'
        self.ids.b_lista_c_der.text = 'Aceptar'
        if not self.listando_claves:
            self.listando_claves = True
            self.titulo_lista = 'Claves'
            if not self.lista_claves_cargadas:
                del self.lista_claves[:]
                for c in self.clave: self.lista_claves.append(ClaveItem(text=c))
                self.lista_claves_cargadas = True
        self.marca_claves(origen)
        self.rellena_claves(cuales)
        #self.titulo_lista = 'Claves'
        self.eligiendo = True
        self.current = 'sc_lista_claves'
        if platform == 'android': android.hide_keyboard()

    def chequeos(self):
        reg = self.ids.i_item_alta.text + \
              self.ids.i_memo_alta.text + \
              self.ids.i_claves_alta.text
        if reg == "":
            self.aviso('Registro vacío')
            return False
        if reg.count(SEP):
            self.aviso('No se puede usar ' + SEP)
            return False
        return True

    def eliminar_registros(self, confirmado=False, modo=''):
        if not confirmado:
            if modo == 'uno':
                self.confirmacion('¿Eliminar el registro?', 'elim_un_reg')
            else:
                self.confirmacion('¿Eliminar ' + str(len(self.dic_items)) + ' registros?', 'elim_n_regs')
            return
        if modo == 'uno':
            a_eliminar = [self.dic_items[self.ids.i_item.text]]
        else:
            a_eliminar = self.dic_items.values()
            a_eliminar.sort(reverse = True)
        for i in a_eliminar:
            self.registros.pop(i)
            self.items.pop(i)
            self.memos.pop(i)
            self.claves.pop(i)
        if self.graba_lista(self.abierto+TEMP, self.registros):
            rename(self.directorio+self.abierto+TEMP, self.directorio+self.abierto+FICH)
            self.num_lineas = str(int(self.num_lineas) - len(a_eliminar))
            self.aviso('Registro(s) eliminado(s)')
        else:
            self.abrir_archivo(self.abierto, incorporar=False)
        self.current = 'sc_menu_principal'

    def existe_fichero(self, nombre):
        if nombre+FICH in listdir(self.directorio):
            self.aviso('Ya existe ese fichero')
            return True
        return False

#    def exportar(self):
#        self.confirmacion('Opciones de exportación', 'exportar')

    def exportar_existente(self, nombre=''):
        if not nombre:
            self.selec_archivo('Archivo al que añadir')
            return
        try:
            F = open(self.directorio+nombre+FICH, 'a')
        except:
            self.aviso('No puedo abrir fichero')
            return
        regis = [self.registros[i] for i in self.dic_items.values()]
        try:
            for r in regis: F.write(r.encode('utf-8') + '\n')
        except:
            self.aviso('No puedo escribir en fichero')
            return
        finally:
            F.close()
        self.current = 'sc_menu_principal'
        self.aviso('Registros añadidos')

    def exportar_nuevo(self, nombre=''):
        if not nombre:
            self.dialogo('Nombre del fichero', 'fichero_exportar')
            return
        if self.existe_fichero(nombre): return
        regis = [self.registros[i] for i in self.dic_items.values()]
#        try:
            # F = open(self.directorio + nombre + FICH, 'w')
        # except:
            # self.aviso('No puedo crear fichero')
            # return
        # try:
            # for r in regis: F.write(r.encode('utf-8') + '\n')
        # except:
            # self.aviso('No puedo escribir fichero')
            # return
        # F.close()
        if self.graba_lista(nombre+FICH, regis):
            self.aviso('Exportados ' + str(len(regis)) + ' registros')

    def graba_lista(self, nombre, lista):
        try:
            F = open(self.directorio + nombre, 'w')
        except:
            self.aviso('No puedo crear fichero')
            return False
        try:
            for r in lista: F.write(r.encode('utf-8') + '\n')
        except:
            self.aviso('No puedo escribir fichero')
            remove(self.directorio + nombre)
            return False
        F.close()
        return True

    def fichero_nuevo(self, nombre=''):
        if not nombre:
            self.dialogo('Nombre del nuevo fichero', 'fichero_nuevo')
            return
        if self.existe_fichero(nombre): return
        try:
            open(self.directorio + nombre + FICH, 'w').close()
        except:
            self.aviso('No puedo crear fichero')
            return
        if self.abrir_archivo(nombre, incorporar=False):
            self.jstore.put("pim", ultimo=nombre, directorio=self.directorio)
            self.num_lineas = '0'
            self.current = 'sc_menu_principal'

    def grabar(self, modo=""):
        if modo=='modif' and not self.modificando:
            self.aviso('No está modificando')
            return
        if modo!='renom' and not self.chequeos(): return
        try: F = open(self.directorio + self.abierto + TEMP, 'w')
        except:
            self.aviso('No puedo crear fichero')
            return
        if modo != 'renom':
            reg = self.ids.i_item_alta.text.strip() + SEP + \
                  self.ids.i_memo_alta.text.rstrip().replace('\n',' ^ ') + SEP + \
                  self.ids.i_claves_alta.text.replace(',',SEP)
            if modo == 'nuevo':
                self.registros.append(reg)
                self.items.append(self.ids.i_item_alta.text)
                self.memos.append(self.ids.i_memo_alta.text.replace('\n',' ^ '))
                self.claves.append(self.ids.i_claves_alta.text.split(','))
            elif modo == 'modif':
                self.registros[self.reg] = reg
                self.items[self.reg] = self.ids.i_item_alta.text
                self.memos[self.reg] = self.ids.i_memo_alta.text.replace('\n',' ^ ')
                self.claves[self.reg] = self.ids.i_claves_alta.text.split(',')
        try:
            for r in self.registros: F.write(r.encode('utf-8') + '\n')
        except UnicodeEncodeError:
            try: remove(self.directorio + self.abierto+TEMP)
            except: pass
            self.aviso('Hay caracteres inválidos')
            return
        except:
            #self.aviso('No puedo escribir fichero')
            try: remove(self.directorio + self.abierto+TEMP)
            except: pass
            self.aviso(str(sys.exc_info()[0]))
            return
        F.close()
        rename(self.directorio + self.abierto+TEMP, self.directorio + self.abierto+FICH)
        if modo == 'nuevo': self.num_lineas = str(int(self.num_lineas) + 1)
        self.current = 'sc_menu_principal'
        if modo == 'renom': self.aviso('Clave renombrada')

    def importar(self, nombre):
        if self.abrir_archivo(nombre, incorporar=True):
            if self.graba_lista(self.abierto+TEMP, self.registros):
                rename(self.directorio+self.abierto+TEMP, self.directorio+self.abierto+FICH)
                self.aviso('Registros importados')
        else:
            self.abrir_archivo(self.abierto, incorporar=False)
        self.current = 'sc_menu_principal'

    def limpia_i_buscar_cadena(self):
        self.i_buscar_cadena.text = ""

    def limpia_b_buscar_claves(self):
        if self.b_buscar_claves.text != "":
            self.b_buscar_claves.text = ""
            for c in self.lista_claves: c.deselect()
            self.listando_claves = False

    def limpia_busqueda(self):
        self.limpia_i_buscar_cadena()
        self.limpia_b_buscar_claves()

    def lista_elegido(self, boton, texto):
        if self.titulo_lista.startswith('Registros encontrados'):
            self.reg = self.dic_items[texto]
            self.ids.i_item.text = self.items[self.reg]
            self.ids.i_memo.text = self.memos[self.reg].replace(' ^ ','\n')
            self.ids.i_claves.text = ','.join(self.claves[self.reg])
            self.ids.i_item.readonly = True
            self.ids.i_memo.readonly = True
            self.ids.i_claves.readonly = True
            self.current = 'sc_registro'
        elif self.titulo_lista == 'Claves':
            #self.claves_seleccionadas.append('kkk'); return
            #~ cla_selec = [c.text for c in self.ids.lis_panta.adapter.data if c.is_selected]
            if texto in self.claves_seleccionadas:
                self.claves_seleccionadas.remove(texto)
                for c in self.ids.lis_c_panta.adapter.data:
                    if c.text == texto: c.is_selected = False
            else:
                self.claves_seleccionadas.append(texto)
                for c in self.ids.lis_c_panta.adapter.data:
                    if c.text == texto: c.is_selected = True
            #~ cla_selec = [c.text for c in self.ids.lis_panta.adapter.data if c.is_selected]
        elif self.titulo_lista == 'Elegir archivo':
            if self.abrir_archivo(texto, incorporar=False):
#                self.jstore.put("pim", directorio='/mnt/sdcard/PIM/', ultimo=texto)
                self.jstore.put("pim", directorio=self.directorio, ultimo=texto)
                self.current = 'sc_menu_principal'
        elif self.titulo_lista == 'Archivo a importar':
            self.importar(texto)
        elif self.titulo_lista == 'Archivo a borrar':
            self.borrar_fich(confirmado=False, nombre=texto)
        elif self.titulo_lista == 'Clave a renombrar':
            self.clave_renombrar = texto
            self.clave_nuevo_nombre("")
        elif self.titulo_lista == 'Archivo al que añadir':
            self.exportar_existente(nombre=texto)


    def marca_claves(self, origen):
        if origen == 'buscar':
            self.claves_buscando = True
            if self.ids.b_buscar_claves.text: self.claves_seleccionadas = self.ids.b_buscar_claves.text.split(',')
            else: self.claves_seleccionadas = []
        else:
            self.claves_buscando = False
            if not self.clave_nueva:
                if self.ids.i_claves_alta.text: self.claves_seleccionadas = self.ids.i_claves_alta.text.split(',')
                else: self.claves_seleccionadas = []
            else:
                self.clave_nueva = False
        for cl in self.lista_claves:
            cl.is_selected = True if cl.text in self.claves_seleccionadas else False

    def limpia_claves_vacias(self):
        for i in range(len(self.registros)):
            if self.registros[i].count(SEP) > 2:
                self.registros[i] = self.registros[i].rstrip(SEP+' ')
                while self.registros[i].count(SEP) < 2:
                    self.registros[i] += SEP
        if self.graba_lista(self.abierto+TEMP, self.registros):
            rename(self.directorio+self.abierto+TEMP, self.directorio+self.abierto+FICH)
            self.current = 'sc_menu_principal'
            self.aviso('Claves limpiadas')
        self.cargado = False

    def modificar(self):
        self.ids.i_item_alta.text = self.ids.i_item.text
        self.ids.i_memo_alta.text = self.ids.i_memo.text
        self.ids.i_claves_alta.text = self.ids.i_claves.text
        self.modificando = True
        self.current = 'sc_alta'

    def orden_archivo(self, orden):
        self.registros.sort(reverse=(orden=='des'), key=lambda s: s.lower())
        if self.graba_lista(self.abierto+TEMP, self.registros):
            rename(self.directorio+self.abierto+TEMP, self.directorio+self.abierto+FICH)
            self.current = 'sc_menu_principal'
            self.aviso('Archivo ordenado')
            #self.cargado = False

    def orden_lista(self, orden):
        self.ids.lis_panta.adapter.data.sort()
        if orden == 'des': self.ids.lis_panta.adapter.data.reverse()

    def panta_buscar(self):
        if self.abierto:
            if not self.cargado: self.carga_listas()
            self.ids.titulo_sc_buscar.text = 'Buscando en ' + self.titulo_fichero
            self.current = 'sc_buscar'
            self.ids.i_buscar_cadena.focus = True

    def rellena(self, tipo=""):
        #~ self.lis_panta.item_strings = ['wefrewr', 'klsjf lkj f']
        #~ self.lis_panta.adapter.data.clear()
        #self.titulo_lista = 'Ficheros disponibles'
        del self.ids.lis_panta.adapter.data[:]
        if tipo == "ficheros":
            #~ self.ids.lis_panta.adapter.data = self.lista
            self.ids.lis_panta.adapter.cls = BotonDeLista
        else:
            self.ids.lis_panta.adapter.cls = LabelDeLista
        self.ids.lis_panta.adapter.data.extend(self.lista)
        self.ids.lis_panta._trigger_reset_populate()

    def rellena_claves(self, cuales):
        del self.ids.lis_c_panta.adapter.data[:]
        if cuales == 'todas':
            self.ids.lis_c_panta.adapter.data.extend(self.lista_claves)
        elif cuales == 'marcadas':
            self.ids.lis_c_panta.adapter.data.extend(c for c in self.lista_claves if c.text in self.claves_seleccionadas)
        else:
            letra = cuales.lower()
            self.ids.lis_c_panta.adapter.data.extend(c for c in self.lista_claves if c.text.lower()>=letra)
        self.ids.lis_c_panta._trigger_reset_populate()

    def args_converter(self, index, data_item):
        #~ texto = data_item
        #~ return {'texto': texto}
        return {'text': data_item}

    def args_converter_claves(self, index, data_item):
        #~ texto = data_item.text
        #~ return {'texto': texto}
        return {'text': data_item.text}

    def renombrar_clave(self):
        if not self.cargado: self.carga_listas()
        self.clave_renombrar = ""
        #self.ids.lis_c_panta.adapter = ListAdapter(data=[], cls=BotonDeLista, args_converter=self.args_converter_claves)
        self.ids.lis_c_panta.adapter.selection_mode = 'single'
        self.titulo_lista = 'Clave a renombrar'
        self.ids.b_lista_c_izq.text = 'Menu'
        self.ids.b_lista_c_cen.text = ''
        self.ids.b_lista_c_der.text = ''
        self.ids.b_lista_c_over.text = 'Cancelar'
        if not self.lista_claves_cargadas:
            del self.lista_claves[:]
            for c in self.clave: self.lista_claves.append(ClaveItem(text=c))
            self.lista_claves_cargadas = True
        self.rellena_claves('todas')
        self.current = 'sc_lista_claves'

    def traduce(self, s):
        s = s.encode('utf-8')
        s = s.replace('á','a').replace('é','e').replace('í','i')\
             .replace('ó','o').replace('ú','u').replace('ñ','n')\
             .replace('ç','c')
        return s.decode('utf-8')