Example #1
0
class FiltredListScreen(Screen):
    def __init__(self, **kw):
        super(FiltredListScreen, self).__init__(**kw)

    def on_enter(self):  # Будет вызвана в момент открытия экрана

        self.layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
        self.layout.bind(minimum_height=self.layout.setter('height'))
        back_button = Button(text='< Назад в главное меню',
                             on_press=lambda x: set_screen('main'),
                             size_hint_y=None,
                             height=dp(40))
        self.layout.add_widget(back_button)
        root = RecycleView(size_hint=(1, None),
                           size=(Window.width, Window.height))
        root.add_widget(self.layout)
        self.add_widget(root)

        # for f, d in sorted(dic_foods.items(), key=lambda x: x[1]):
        #     fd = f.decode('u8') + ' ' + (datetime.fromtimestamp(d).strftime('%Y-%m-%d'))
        #     btn = Button(text=fd, size_hint_y=None, height=dp(40))
        #     self.layout.add_widget(btn)

    def on_leave(self):  # Будет вызвана в момент закрытия экрана

        self.layout.clear_widgets()  # очищаем список
class BotListArea(ScrollView):
    def __init__(self, **kwargs):
        super(BotListArea, self).__init__(**kwargs)
        self.layout = GridLayout(cols=1,
                                 spacing=10,
                                 size_hint=(1, 1),
                                 pos_hint={
                                     'center_x': .5,
                                     'center_y': .5
                                 })
        self.layout.bind(minimum_height=self.layout.setter('height'))
        self.add_widget(self.layout)

    def refreshBots(self, bots):
        self.layout.clear_widgets()

        def callback(instance):
            botnum = int(instance.text.split(" ")[1])
            App.get_running_app().selectBot(botnum)
            getSecondWindow()

        for b in bots:
            label = "Bot " + str(b)
            btn = Button(text=label, size_hint=(1, 1))
            btn.bind(on_press=callback)
            self.layout.add_widget(btn)
Example #3
0
class FriendsList(GridLayout):
    def __init__(self):
        self.root = GridLayout(cols=1)
        self.scroll = ScrollView(size_hint=(1, .7))
        self.friends_grid = GridLayout(cols=1)
        
        refresh_button = Button(text="refresh")
        refresh_button.bind(on_press=self.refresh_friends)

        self.root.add_widget(refresh_button) 
        self.fill_friends_grid()        
        self.scroll.add_widget(self.friends_grid)
        self.root.add_widget(self.scroll)

    def fill_friends_grid(self):
        self.friends_grid.clear_widgets()
        app = App.get_running_app()
        for i in app.nodes:
            friend = GridLayout(cols=5)
            friend.add_widget(Label(text=i[0]))
            friend.add_widget(Label(text=i[1]))
            friend.add_widget(Label(text=i[2]))
            friend.add_widget(Label(text=i[3]))
            #friend.add_widget() dm button class
            self.friends_grid.add_widget(friend)
    
    def refresh_friends(self, instance):
        self.fill_friends_grid()
Example #4
0
class DrinkersListWidget(ScrollView):
    def __init__(self, db, **kwargs):
        """
        :param Db db:
        """
        # https://kivy.org/doc/stable/api-kivy.uix.scrollview.html
        # Window resize recursion error while using ScrollView? https://github.com/kivy/kivy/issues/5638
        # size_hint=(1, None) correct? size_hint=(1, 1) is default.
        # self.parent.bind(size=self.setter("size")), once the parent assigned?
        super(DrinkersListWidget, self).__init__(**kwargs)
        self.db = db
        self.layout = GridLayout(cols=1, spacing=2, size_hint_y=None)
        # Make sure the height is such that there is something to scroll.
        self.layout.bind(minimum_height=self.layout.setter('height'))
        self.add_widget(self.layout)
        self.update_all()

    @run_in_mainthread_blocking()
    def update_all(self):
        self.layout.clear_widgets()
        for drinker_name in sorted(self.db.get_drinker_names()):
            self.layout.add_widget(DrinkerWidget(db=self.db, name=drinker_name, size_hint_y=None, height=30))

    @run_in_mainthread_blocking()
    def update_drinker(self, drinker_name):
        """
        :param str drinker_name:
        """
        for widget in self.layout.children:
            assert isinstance(widget, DrinkerWidget)
            if widget.name == drinker_name:
                widget.update()
                return
        raise Exception("Unknown drinker: %r" % (drinker_name,))
Example #5
0
class SortedListFood(Screen):
    def __init__(self, **kw):
        super(SortedListFood, self).__init__(**kw)

    def on_enter(self):  # Будет вызвана в момент открытия экрана

        self.layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
        self.layout.bind(minimum_height=self.layout.setter('height'))
        back_button = Button(text='< Go BAck',
                             on_press=lambda x: set_screen('menu'),
                             size_hint_y=None, height=dp(40))
        self.layout.add_widget(back_button)
        root = RecycleView(size_hint=(1, None), size=(Window.width,
                                                      Window.height))
        root.add_widget(self.layout)
        self.add_widget(root)

        dic_foods = ast.literal_eval(
            App.get_running_app().config.get('General', 'user_data'))

        for f, d in sorted(dic_foods.items(), key=lambda x: x[1]):
            fd = f.decode('u8') + ' ' + (datetime.fromtimestamp(d).strftime('%Y-%m-%d'))
            btn = Button(text=fd, size_hint_y=None, height=dp(40))
            self.layout.add_widget(btn)

    def on_leave(self):  # Будет вызвана в момент закрытия экрана

        self.layout.clear_widgets()  # очищаем список
Example #6
0
class AppList(StackLayout):

    def __init__(self, app):
        super(AppList, self).__init__(spacing=2, size_hint=(None, None))
        self.app = app

        self.title = Label(text="No title yet", height=30)
        self.add_widget(self.title)

        self.add_buttons()

        scroll = ScrollView(size_hint_y=None, height=600 - self.height)
        self.add_widget(scroll)

        self.layout = GridLayout(cols=1, size_hint_y=None)
        self.layout.bind(minimum_height=self.layout.setter('height'))
        scroll.add_widget(self.layout)

    def add_buttons(self):
        pass

    def clear_list(self):
        self.layout.clear_widgets()

    def add_item(self, item):
        item.size_hint_y = None
        item.height = 40
        self.layout.add_widget(item)
        return item
Example #7
0
class ContactTab(TabbedPanelItem):
    logic = ObjectProperty(None)

    def __init__(self, **kargs):
        super(ContactTab, self).__init__(**kargs)
        self.logic = App.get_running_app().logic
        self.build_interface()

    def build_interface(self):
        self.layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
        self.layout.clear_widgets()
        self.layout.bind(minimum_height=self.layout.setter('height'))
        for contact in self.logic.contacts:
            # dont add yourself to contact-list!
            if str(contact) == self.logic.name:
                continue
            btn = Button(text=contact,
                         size_hint_y=None,
                         height=40,
                         on_press=self.logic.btn_call_up)
            self.layout.add_widget(btn)
        self.content = ScrollView()
        self.content.add_widget(self.layout)

    def contact_tab_update(self):
        self.build_interface()
Example #8
0
	def prev_recordings(self):
		"""
		Show a list of previous recordings.
		"""
		self.clear_widgets()
		self.record_layout.clear_widgets()
		self.list_layout.clear_widgets()
		#sub_layout = BoxLayout(orientation='vertical')
		sub_layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
		sub_layout.bind(minimum_height=sub_layout.setter('height'))
		sub_layout.clear_widgets()
		titles = []
		paths = []
		for filename in os.listdir("/sdcard/operator/recordings"):
			if filename.endswith(".wav"):
				paths.append(os.path.join("/sdcard/operator/recordings/", filename))
				name = filename[:-4]
				info = name.split('-')
				formatted_name = info[3] + ":" + info[4] + ":" + info[5] + " on " + info[1] + "/"+info[2] + "/" + info[0]
				titles.append(formatted_name)
		for title, path in zip(titles, paths):
			play_button = Button(text=title, size_hint_y=None, height=160)
			play_button.bind(on_release=functools.partial(self.play_prev, path))
			sub_layout.add_widget(play_button)
		return_btn = Button(text="Previous", on_release=lambda x: self.show_menu(), size_hint_y=None, height=100)
		#self.list_layout.add_widget(sub_layout)
		self.record_layout.add_widget(sub_layout)
		self.record_layout.add_widget(return_btn)
		self.add_widget(self.record_layout)
Example #9
0
class ViewListScreen(MyScreen):
    def __init__(self, **kwargs):
        super(ViewListScreen, self).__init__(**kwargs)
        self.sv = ScrollView()
        self.content_box.add_widget(self.sv)



        self.list_grid = GridLayout(cols = 1,
                                size_hint_y = None,
                                orientation = 'vertical')
        self.sv.add_widget(self.list_grid)

        self.bind(on_pre_enter= self.prepare_yourself)
    
    def prepare_yourself(self,*args):
        
        self.list_grid.clear_widgets()

        c_list = App.get_running_app().root.current_list
        self.list_grid.height = len(c_list)*40 #HARDCODE

        for e,spell in enumerate(c_list):
            spell['button_card'].id = str(e)
            self.list_grid.add_widget(spell['button_card'])
Example #10
0
class StationList(ScrollView):
    layout = None
    collection = None

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

        self.layout = GridLayout(cols=1, size_hint=(None, None))
        self.layout.bind(minimum_height=self.layout.setter('height'))
        self.add_widget(self.layout)

    def update_list(self, collection):
        if collection == self.collection:
            return

        self.collection = collection
        self.layout.clear_widgets()
        for station in collection:
            item = StationListingItem(station, self.layout, self.on_station_select, size=(self.width, 225), text_size=(self.width*.9, 255))
            self.layout.add_widget(item)

    def add_station_selection_listener(self, callback):
        self.callback = callback

    def on_station_select(self, station):
        self.callback(station)
Example #11
0
class History(Screen):
    def __init__(self, **kw):
        super(History, self).__init__(**kw)

    def on_enter(self):  # Будет вызвана в момент открытия экрана

        self.layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
        self.layout.bind(minimum_height=self.layout.setter('height'))
        back_button = Button(text='< Назад в главное меню',
                             on_press=lambda x: set_screen('menu'),
                             size_hint_y=None, height=dp(40))
        self.layout.add_widget(back_button)
        root = RecycleView(size_hint=(1, None), size=(Window.width,
                                                      Window.height))
        root.add_widget(self.layout)
        self.add_widget(root)

        dic_foods = ast.literal_eval(
            App.get_running_app().config.get('General', 'user_data'))

        i = 0
        rand = random.randint(10,20)
        for f, d in sorted(dic_foods.items(), key=lambda x: x[1]):
            i += 1
            fd = f.decode('u8')
            btn = Button(text=fd, size_hint_y=None, height=dp(40))
            if i == rand:
                btn = Button(text='Try catch token!',
                             on_press=lambda x: set_screen('get_token'),
                             size_hint_y=None, height=dp(40))
                self.layout.add_widget(btn)
            else:
                self.layout.add_widget(btn)
    def on_leave(self):  # Будет вызвана в момент закрытия экрана
        self.layout.clear_widgets()  # очищаем список
Example #12
0
class CaterpillarList(ScrollView):
    def __init__(self, **kwargs):
        super(CaterpillarList, self).__init__(**kwargs)
        self.caterpillars = []
        self.bind(size=self.draw)
        self.box = GridLayout(orientation="vertical",
                              cols=2,
                              size_hint_y=None,
                              spacing=10)
        self.box.bind(minimum_height=self.box.setter('height'))
        self.add_widget(self.box)

    def reset(self):
        self.caterpillars = []
        self.draw()

    def add(self, caterpillar):
        if caterpillar in self.caterpillars:
            self.caterpillars.remove(caterpillar)
        self.caterpillars = [caterpillar] + self.caterpillars
        self.draw()

    def draw(self, *args):
        self.box.clear_widgets()
        x, y = self.size
        if x > y: cols = 2
        else: cols = 1
        self.box.cols = cols
        for guess in self.caterpillars:
            self.box.add_widget(
                Caterpillar(chain=guess,
                            size_hint_y=None,
                            size=(x, x / 7 / cols)))
        self.scroll_y = 1
class CaterpillarList(ScrollView):

    def __init__(self,**kwargs):
        super(CaterpillarList, self).__init__(**kwargs)
        self.caterpillars=[]
        self.bind(size=self.draw)
        self.box=GridLayout(orientation="vertical",cols=2,size_hint_y=None,spacing=10)
        self.box.bind(minimum_height=self.box.setter('height'))
        self.add_widget(self.box)


    def reset(self):
        self.caterpillars=[]
        self.draw()

    def add(self,caterpillar):
        if caterpillar in self.caterpillars:
            self.caterpillars.remove(caterpillar)
        self.caterpillars=[caterpillar]+self.caterpillars
        self.draw()

    def draw(self,*args):
        self.box.clear_widgets()
        x,y=self.size
        if x>y: cols = 2
        else: cols =1
        self.box.cols=cols
        for guess in self.caterpillars:
            self.box.add_widget(Caterpillar(chain=guess,size_hint_y=None,size=(x,x/7/cols)))
        self.scroll_y=1
Example #14
0
class SearchLayout(BoxLayout):
    def __init__(self, **kwargs):
        super(SearchLayout, self).__init__()
        self.orientation = 'vertical'

        # message
        self.message = Label(text="검색 창", size_hint=(1, 0.05), font_name=FONT_NAME)
        self.add_widget(self.message)

        # emoticon result
        self.emoticon_box = GridLayout(cols=4)
        self.add_widget(self.emoticon_box)

        # tag
        self.input_label = Label(text="아래 검색 키워드를 입력", size_hint=(1, 0.1), font_name=FONT_NAME)
        self.keyword = TextInput(multiline=False, size_hint=(1, 0.1), font_name=FONT_NAME)
        self.add_widget(self.input_label)
        self.add_widget(self.keyword)

        # search button
        self.search = Button(text="검색하기", font_name=FONT_NAME, size_hint=(1, 0.3))
        self.search.bind(on_press=self.search_keyword)
        self.add_widget(self.search)

    def search_keyword(self, instance):
        idx_dict = keywords.get(self.keyword.text)
        self.emoticon_box.clear_widgets()
        self.keyword.text = ''
        if idx_dict:
            for name, idx_list in idx_dict.items():
                grid = BoxLayout(orientation='horizontal')
                self.emoticon_box.add_widget(Label(text=f'{name} -> ', font_name=FONT_NAME))
                for i in idx_list:
                    img = Image(texture=emoticon_dict[name].textures[i], allow_stretch=True)
                    self.emoticon_box.add_widget(img)
Example #15
0
class SortedListFood(Screen):
    def __init__(self, **kw):
        super(SortedListFood, self).__init__(**kw)

    def on_enter(self):  # Будет вызвана в момент открытия экрана

        self.layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
        self.layout.bind(minimum_height=self.layout.setter('height'))
        back_button = Button(text='< Назад к игре',
                             on_press=lambda x: set_screen('add_food'),
                             size_hint_y=None,
                             height=dp(40))
        self.layout.add_widget(back_button)
        root = RecycleView(size_hint=(1, None),
                           size=(Window.width, Window.height))
        root.add_widget(self.layout)
        self.add_widget(root)

        dic_foods = ast.literal_eval(App.get_running_app().config.get(
            'General', 'user_data'))
        file = 'file_words.pk'
        with open(file, 'rb') as fi:
            time = pickle.load(fi)
        for f, d in sorted(dic_foods.items(), key=lambda x: x[1]):
            fd = f.decode('u8')
            if time > d:
                pass
            else:
                btn = Button(text=fd, size_hint_y=None, height=dp(40))
                self.layout.add_widget(btn)

    def on_leave(self):  # Будет вызвана в момент закрытия экрана

        self.layout.clear_widgets()  # очищаем список
Example #16
0
class DiagramScreen(Screen):
    def __init__(self, screen_manager, **kwargs):
        super(DiagramScreen, self).__init__(**kwargs)
        self.screen_manager = screen_manager

        self.main_layout = GridLayout(cols=1)
        self.header_layout = GridLayout(cols=2, size_hint=(1, 0.1))
        self.info_layout = GridLayout(cols=1, size_hint=(1, 1))
        self.back_button = Button(text='<=', size_hint=(0.1, 1))
        self.back_button.on_press = self.go_to_contact_list
        self.label = CLabel(text='', size_hint=(0.9, 1))
        self.header_layout.add_widget(self.back_button)
        self.header_layout.add_widget(self.label)
        self.main_layout.add_widget(self.header_layout)
        self.main_layout.add_widget(self.info_layout)
        self.add_widget(self.main_layout)

    def set_label(self, label):
        self.show_label(label)
        if label == 'Diagram all messages':
            self.show_chart('all_messages.jpg')

    def show_label(self, label):
        self.label.text = f'{label}'

    def show_chart(self, name):
        self.info_layout.clear_widgets()
        path_img = get_path_diagram(name)
        if os.path.exists(path_img):
            img = Image(source=path_img)
            self.info_layout.add_widget(img)

    def go_to_contact_list(self):
        self.screen_manager.current = 'statistic'
Example #17
0
class CharacterSpellsTab(TabbedPanelItem):
    def __init__(self, character, *args, **kwargs):
        super(CharacterSpellsTab, self).__init__(*args, **kwargs)
        self.character = character
        self.text = 'Spells'
        self.content = BoxLayout(orientation='vertical')
        self.spacing = 10
        self.spells = ScrollView(size=(Window.width, Window.height))

        self.layout = GridLayout(cols=1, spacing=1, size_hint_y=None)
        self.layout.bind(minimum_height=self.layout.setter('height'))
        self.spells.add_widget(self.layout)

        def add_spell(button):
            popup = AddSpellPopup(self)
            popup.open()

        buttons = BoxLayout(orientation='horizontal', size_hint=(1, .1))
        buttons.add_widget(Button(text='Add spell', on_press=add_spell))
        self.content.add_widget(buttons)
        self.content.add_widget(SpellHeader())
        self.content.add_widget(self.spells)

        self.set_spells()

    def set_spells(self):
        self.layout.clear_widgets()

        spells = (session.query(SpellbookEntry).filter(
            SpellBookEntry.character == self.character.name).all())

        for spell in spells:
            self.layout.add_widget(
                SpellbookEntry(self, spell, height=60, size_hint_y=None))
        self.layout.bind(minimum_height=self.layout.setter('height'))
Example #18
0
class FruitDetailScreen(FruitScreen):
    fruit_name=''
    def __init__(self, **kwargs):
        super(FruitDetailScreen, self).__init__(**kwargs)

        btn = Button(text='back', size_hint=(.15,.07),
                             pos_hint={'center_x': .2, 'center_y':.9},
                             background_color=BUTTON_COLOR,
                             color=BLACK,
                             on_release=self.on_release)
        self.add_widget(btn)

        self.slate =GridLayout(cols=1, pos_hint={'center_x': .5, 'center_y':.4},
                                                size_hint=(.5, .4))
        self.add_widget(self.slate)

    def on_enter(self):
        values_dict = STORAGE.get(self.fruit_name, {})
        lbl = FruitDetailLabel(text='name: %s' % self.fruit_name)
        self.slate.add_widget(lbl)

        for k  in WANTED_KEYS:
            v = values_dict.get(k, '')
            lbl = FruitDetailLabel(text='%s: %s' % (k,v))
            self.slate.add_widget(lbl)

    def on_leave(self):
        self.slate.clear_widgets()
        self.fruit_name=''

    def on_release(self, event):
        self.manager.current = self.manager.previous()
Example #19
0
class DatePicker(BoxLayout):
    def __init__(self, **kwargs):
        super(DatePicker, self).__init__(**kwargs)
        self.date = date.today()
        self.orientation = "vertical"

        self.header = BoxLayout(orientation='horizontal', size_hint=(1, 0.2))
        self.body = GridLayout(cols=7)
        self.add_widget(self.header)
        self.add_widget(self.body)

        self.populate_body()
        self.populate_header()

    def populate_header(self):
        self.header.clear_widgets()
        self.previous_month = Button(text="<")
        self.next_month = Button(text=">")
        self.current_month = Label(text=repr(self.date), size_hint=(2, 1))

        self.header.add_widget(self.previous_month)
        self.header.add_widget(self.current_month)
        self.header.add_widget(self.next_month)

    def populate_body(self):
        self.body.clear_widgets()
        date_cursor = date(self.date.year, self.date.month, 1)
        while date_cursor.month == self.date.month:
            self.date_label = Label(text=str(date_cursor.day))
            self.body.add_widget(self.date_label)
            date_cursor += timedelta(days=1)
Example #20
0
class LearnScreen(Screen, Widget):
    def __init__(self, **kwargs):
        super(LearnScreen, self).__init__(**kwargs)
        global wp
        fl = FloatLayout()
        bl = BoxLayout(pos_hint={
            "x": 0,
            "y": 0
        },
                       size_hint=(1, 0.15),
                       padding=10)
        btn_first = Button(text="First", font_size=24, on_press=self.first)
        btn_next = Button(text="Next", font_size=24, on_press=self.next)
        btn_test = Button(text="Dictation", font_size=24, on_press=self.test)
        bl.add_widget(btn_first)
        bl.add_widget(btn_next)
        bl.add_widget(btn_test)
        words = json.load(open("words.json"))

        self.n = 1
        self.n_max = int(len(list(words.keys())) / wp)
        if isinstance(self.n_max, int):
            self.n_max += 1
        self.grid = GridLayout(cols=2,
                               pos_hint={
                                   "x": 0,
                                   "y": 0.15
                               },
                               size_hint=(1, 0.85))
        words1 = list(words.keys())[0:wp]
        for i in words1:
            self.grid.add_widget(Label(text=i))
            self.grid.add_widget(Label(text=words[i][0]))
        fl.add_widget(bl)
        fl.add_widget(self.grid)
        self.add_widget(fl)

    def test(self, instance):
        global sm
        sm.current = "test"

    def first(self, instance):
        self.n = 1
        self.grid.clear_widgets()
        words = json.load(open("words.json"))
        words1 = list(words.keys())[0:wp]
        for i in words1:
            self.grid.add_widget(Label(text=i))
            self.grid.add_widget(Label(text=words[i][0]))

    def next(self, instance):
        if self.n < self.n_max:
            self.grid.clear_widgets()
            words = json.load(open("words.json"))
            self.n += 1
            wordsn = list(words.keys())[wp * (self.n - 1):wp * self.n]
            for i in wordsn:
                self.grid.add_widget(Label(text=i))
                self.grid.add_widget(Label(text=words[i][0]))
Example #21
0
class SortedListFood(Screen):
    def __init__(self, **kw):
        super(SortedListFood, self).__init__(**kw)
        self.TodayOrNot = Button(text='Сегодня', size_hint_y=None, height=dp(40))
        self.Tod = False

    def Today_func(self, btn):
        self.Tod = not self.Tod
        self.layout.clear_widgets()
        if self.Tod:
            self.TodayOrNot.text = 'Всё время'
        else:
            self.TodayOrNot.text = 'Сегодня'
        self.build()

    def build(self):
        self.layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
        self.layout.bind(minimum_height=self.layout.setter('height'))
        back_button = Button(text='< Назад в главное меню',
                             on_press=lambda x: set_screen('menu'),
                             size_hint_y=None, height=dp(40))
        self.layout.add_widget(back_button)
        self.TodayOrNot.bind(on_press=self.Today_func)
        self.layout.add_widget(self.TodayOrNot)
        root = RecycleView(size_hint=(1, None), size=(Window.width,
                                                      Window.height))
        root.add_widget(self.layout)
        self.add_widget(root)

        dic_foods = ast.literal_eval(
            App.get_running_app().config.get('General', 'user_data'))
        TodayCalories = 0.0
        TodayProt = 0.0
        TodayFat = 0.0
        TodayCarboh = 0.0
        arr = []
        for f, d in sorted(dic_foods.items(), key=lambda x: x[1], reverse=True):
            if datetime.fromtimestamp(d).strftime('%Y-%m-%d') == datetime.today().strftime('%Y-%m-%d') or not self.Tod:
                product = f.decode('u8')
                fd = product + ' ' + (datetime.fromtimestamp(d).strftime('%Y-%m-%d'))
                TodayCalories += float(product[product.find("гр., ") + 5:product.find("ккал") - 1])
                TodayProt += float(product[product.find("ккал, ") + 6:product.find("белк") - 1])
                TodayFat += float(product[product.find("белк, ") + 6:product.find("жир") - 1])
                TodayCarboh += float(product[product.find("жир, ") + 5:product.find("углв") - 1])
                btn = Button(text=fd, size_hint_y=None, height=dp(40))
                arr.append(btn)
        if self.Tod:
            btn1 = Button(text="За сегодня вы съели: %s ккал, %s белк, %s жир, %s углв"
                               % (TodayCalories, TodayProt, TodayFat, TodayCarboh), size_hint_y=None, height=dp(40))
            self.layout.add_widget(btn1)
        for i in arr:
            self.layout.add_widget(i)

    def on_enter(self):
        self.build()

    def on_leave(self):
        self.layout.clear_widgets()
Example #22
0
class PreparationScreen(Screen):
    def __init__(self, **kwargs):
        Screen.__init__(self, name="Preparation", **kwargs)
        _layout = BoxLayout(orientation='vertical')
        self._question_grid = BoxLayout(orientation='vertical',
                                        size_hint=(1, 0.2))
        _layout.add_widget(self._question_grid)
        self._answer_grid = GridLayout(cols=3, size_hint=(1, 0.4))
        _layout.add_widget(self._answer_grid)
        self.send_btn = Button(text="Send", font_size=36, size_hint=(1, 0.2))
        self.send_btn.bind(on_release=self.on_send)
        _layout.add_widget(self.send_btn)
        self.add_widget(_layout)
        self._questions = []
        self._answers = []

    def init(self, num_questions, num_answers):
        self._question_grid.clear_widgets()
        self._answer_grid.clear_widgets()
        self._questions = [
            TextInput(multiline=False, font_size=36)
            for _ in range(num_questions)
        ]
        for widget in self._questions:
            self._question_grid.add_widget(widget)
        self._answers = [
            TextInput(multiline=False, font_size=28)
            for _ in range(num_answers)
        ]
        for widget in self._answers:
            self._answer_grid.add_widget(widget)

    def on_pre_enter(self, *args):
        client.add_listener(self.game_started_handler)

    def on_pre_leave(self, *args):
        client.remove_listener(self.game_started_handler)

    def on_leave(self, *args):
        self.send_btn.disabled = False
        self.send_btn.text = 'Send'

    def on_send(self, instance: Button):
        questions = [widget.text for widget in self._questions]
        answers = [widget.text for widget in self._answers]
        if all(questions) and all(answers):
            instance.disabled = True
            instance.text = "Waiting for others..."
            client.send({"op": "AddQuestions", "questions": questions})
            client.send({"op": "AddAnswers", "answers": answers})

    def game_started_handler(self, msg):
        if msg.get('op') == 'MainStarted':
            players = [(plr['id'], plr['name']) for plr in msg['players']
                       if plr['id'] != player_id]
            next_screen = GameScreen(players)
            self.manager.add_widget(next_screen)
            self.manager.current = next_screen.name
Example #23
0
class LibraryFood(Screen):
    def __init__(self, **kw):
        super(LibraryFood, self).__init__(**kw)
        self.Liblayout = GridLayout(cols=1, spacing=10, size_hint_y=1)
        self.Liblayout.bind(minimum_height=self.Liblayout.setter('height'))
        self.back_button = Button(text='< Назад',
                                  on_press=lambda x: set_screen('add_food'),
                                  size_hint_y=None, height=dp(40))
        self.Seach_Text = TextInput(text='', multiline=False, height=dp(40),
                                    size_hint_y=None, hint_text="Поиск")
        self.Seach_Btn = Button(text='Поиск', size_hint_y=None, height=dp(40))
        self.Seach_Btn.bind(on_press=self.Search_Func)
        self.Liblayout.add_widget(self.back_button)
        self.Liblayout.add_widget(self.Seach_Text)
        self.Liblayout.add_widget(self.Seach_Btn)
        self.Buflayout = GridLayout(cols=1, spacing=10, size_hint_y=0.75)
        self.add_widget(self.Buflayout)
        self.add_widget(self.Liblayout)

    def on_enter(self):
        self.Seach_Text.text = ''
        self.Buflayout.clear_widgets()

    def Choice(self, btn):
        product = btn.text
        global P
        P.Name = product[0:product.find("(")]
        P.Weight = product[product.find("(") + 1:product.find(" ", product.find("("))]
        P.Calories = product[product.find("гр., ") + 5:product.find("ккал") - 1]
        P.Proteins = product[product.find("ккал, ") + 6:product.find("белк") - 1]
        P.Fats = product[product.find("белк, ") + 6:product.find("жир") - 1]
        P.Carboh = product[product.find("жир, ") + 5:product.find("углв") - 1]
        set_screen('add_food')

    def Search_Func(self, btn):
        Product = self.Seach_Text.text
        translator = Translator()
        result = translator.translate(Product)
        link = 'https://api.nal.usda.gov/fdc/v1/foods/search?query=%s' \
               '&pageSize=5&api_key=BZeMvKQVspWyoAgB3wJxy1MXdq6Ot5WNgvD3K5Bf' % result.text
        #print(link)
        try:
            if requests.get(link).ok:
                response = requests.get(link).text
                response = json.loads(response)
                response = response['foods']
                for i in range(len(response)):
                    prod = Product + "(%s гр., %s ккал, %s белк, %s жир, " \
                                     "%s углв)" % ("100", response[i]['foodNutrients'][3]['value'],
                                                   response[i]['foodNutrients'][0]['value'],
                                                   response[i]['foodNutrients'][1]['value'],
                                                   response[i]['foodNutrients'][2]['value'])
                    btn = Button(text=prod, size_hint_y=None, height=dp(40))
                    btn.bind(on_press=self.Choice)
                    self.Buflayout.add_widget(btn)
        except:
            pass
class FileSearchComponents(FloatLayout):
    def __init__(self, **kwargs):
        super(FileSearchComponents, self).__init__(**kwargs)

        self.search_input = TextInput(multiline=False,
                                      size_hint=(0.20, 0.05),
                                      pos_hint={
                                          'x': 0.025,
                                          'y': 0.45
                                      })
        self.search_input.bind(text=self.on_type)

        self.search_results_container = ScrollView(size_hint=(0.2, 0.25),
                                                   pos_hint={
                                                       'x': 0.025,
                                                       'y': 0.20
                                                   })
        self.search_results = GridLayout(cols=1, size_hint_y=None, height=2000)

        self.search_results_container.add_widget(self.search_results)

        self.add_widget(self.search_input)
        self.add_widget(self.search_results_container)

    # Sends search input text to socket whenever anything is typing within search_input, then displays the results
    def on_type(self, instance, text):
        self.search_results.clear_widgets()

        if len(folder_search_modify) > 0:
            query_result = socketcomm.send_query_to_socket(
                self.search_input.text + " Folder_names: " +
                str(folder_search_modify))
        else:
            query_result = socketcomm.send_query_to_socket(
                self.search_input.text)

        # Splits the aggregate query result into its individual results
        if query_result is not None:
            query_split = query_result.split(',')
            self.search_results.height = len(query_split) * 35
            for data in query_split:
                if len(data) > 2:
                    result_button = Button(text=data.strip())
                    result_button.bind(on_press=self.on_file_collect)
                    self.search_results.add_widget(result_button)

    # Displays the room information of the rooms search result button
    @staticmethod
    def on_file_collect(button):
        if ("Invalid query" in button.text) or ("No results found"
                                                in button.text):
            return

        file_data = socketcomm.collect_exact_query(button.text)

        print("File data: " + file_data)
        rootlayout.root.file_data_display.show_file_data(file_data)
Example #25
0
class MainWindowScreen(Screen):
    def __init__(self, **kwargs):
        super(MainWindowScreen, self).__init__(**kwargs)

        self.language_code = None

        self.layout = GridLayout(cols=1, size_hint_y=None)
        # Make sure the height is such that there is something to scroll.
        self.layout.bind(minimum_height=self.layout.setter('height'))

        self.scroll = ScrollView(size_hint=(1, None),
                                 size=(Window.width, Window.height * 0.60))
        self.scroll.add_widget(self.layout)

        self.add_widget(self.scroll)

    def change_language(self, language):
        print(language)

        for item in LANGUAGES:
            if item['lang'] == language:
                self.language_code = item['code']

        print(self.language_code)

    def find_phrase(self, phrase, key='search'):
        print(phrase)
        if not phrase:
            return

        data = data_p.parse_phrase(phrase, self.language_code)
        self.layout.clear_widgets()

        if len(data):
            for el in data:
                print(el)
                btn = WrappedButton(
                    text=str(el),
                    size_hint_y=None,
                    background_color=[74 / 255, 213 / 255, 237 / 255, 1],
                    font_size=20,
                    font_name='Arial',
                    on_press=partial(sound.pronounce, el))
                self.layout.add_widget(btn)

            for element in self.layout.children:
                print(element)

            if key == 'search':
                db.add_note(phrase, data)  # add to db
            # HistoryScreen().load_history_list()  # and update the list of history

        else:
            self.layout.add_widget(
                Label(text='No results',
                      color=[62 / 255.0, 204 / 255.0, 237 / 255.0, 1.0]))
Example #26
0
class SyncMessageLayout(BoxLayout):
    """服务器测试布局"""
    def __init__(self, **kwargs):
        super(SyncMessageLayout, self).__init__(**kwargs)
        self.sync_count_success = 0
        self.sync_count_failure = 0
        self.layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
        self.layout.bind(minimum_height=self.layout.setter('height'))

    def update_url(self, url):
        """更新服务器地址"""
        self.ids['server_url'].text = url

    def sync_messages(self):
        """同步服务器信息"""
        url = self.ids['server_url'].text + 'height.php'  # 获取信息高度(条目数)
        self.sync_count_success = 0
        self.sync_count_failure = 0
        self.ids['scrlv'].clear_widgets()
        self.layout.clear_widgets()
        req = UrlRequest(url=url, on_success=self.get_height_success)

    def get_height_success(self, req, values):
        """获取信息高度成功后逐条目同步信息"""
        all_hash = json.loads(values)
        # self.ids['message_list'].text = "获取信息高度成功< " + str(len(all_hash)) + "> \n"
        for h in all_hash:
            if h not in message_hash:
                url = self.ids[
                    'server_url'].text + 'get_hash.php' + '?hash=' + h
                req = UrlRequest(url=url, on_success=self.request_success)

    def request_success(self, req, values):
        """请求成功"""
        self.sync_count_success += 1
        dat = json.loads(str(values))
        message = MMMessage(json.loads(dat))
        msg = MessageLayout(message)
        msg.update()
        self.ids['scrlv'].clear_widgets()
        self.layout.add_widget(msg)
        self.ids['scrlv'].add_widget(self.layout)
        # self.ids['message_list'].text += '信息<' + str(self.sync_count_success) + ">\n" + json.loads(values) + "\n"
        self.ids[
            'sync_statues'].text = '成功同步[color=33ff33]{0}[/color]失败[color=ff3333]{1}[/color]'.format(
                str(self.sync_count_success), str(self.sync_count_failure))

    def request_failure(self, req, result):
        """请求失败"""
        # self.ids['message_list'].text += "请求失败\n"
        self.sync_count_failure += 1
        self.ids[
            'sync_statues'].text = '成功同步[color=33ff33]{0}[/color]失败[color=ff3333]{1}[/color]'.format(
                str(self.sync_count_success), str(self.sync_count_failure))
Example #27
0
class FriendBox(BoxLayout):
    def __init__(self, root_box, *args, **kwargs):
        self.root_box = root_box
        super(FriendBox, self).__init__(*args, **kwargs)
        self.friend_rows = {}

        # create a grid for the scroll view to contain things
        self.layout = GridLayout(cols=1, padding=(10, 15), size_hint=(1, None))
        self.layout.bind(minimum_height=self.layout.setter('height'))
        self.ids.scroller.add_widget(self.layout)

        # listen for spinner events
        self.ids.sort_by.bind(text=self.change_sort)
        self.ids.sort_order.bind(text=self.change_sort)

    def change_sort(self, spinner, text):
        if text == 'Name':
            sort_key = 'name'
        elif text == 'Userid':
            sort_key = 'userid'
        else:
            sort_key = 'status'

        # find all the friends in the friend rows
        friends = [row.friend for row in self.layout.children]
        reverse = self.ids.sort_order.text == '^'
        sort_by(sort_key, friends, reverse)

        # remove old widgets, replace with new ones
        self.layout.clear_widgets()
        self.friend_rows = {}
        self.add_friends(friends)

    def change_status(self, userid, status):
        try:
            self.friend_rows[userid].friend.status = status
        except KeyError:
            # no matching userid, probably a chat room, ignore it
            pass

    def add_friend(self, friend):
        if friend.userid in self.friend_rows:
            return

        row = FriendRow(friend)
        self.friend_rows[friend.userid] = row
        self.layout.add_widget(row)

    def add_friends(self, friends):
        for friend in friends:
            self.add_friend(friend)
Example #28
0
class FriendBox(BoxLayout):
    def __init__(self, root_box, *args, **kwargs):
        self.root_box = root_box
        super(FriendBox, self).__init__(*args, **kwargs)
        self.friend_rows = {}

        # create a grid for the scroll view to contain things
        self.layout = GridLayout(cols=1, padding=(10, 15), size_hint=(1, None))
        self.layout.bind(minimum_height=self.layout.setter('height'))
        self.ids.scroller.add_widget(self.layout)

        # listen for spinner events
        self.ids.sort_by.bind(text=self.change_sort)
        self.ids.sort_order.bind(text=self.change_sort)

    def change_sort(self, spinner, text):
        if text == 'Name':
            sort_key = 'name'
        elif text == 'Userid':
            sort_key = 'userid'
        else:
            sort_key = 'status'

        # find all the friends in the friend rows
        friends = [row.friend for row in self.layout.children]
        reverse = self.ids.sort_order.text == '^'
        sort_by(sort_key, friends, reverse)

        # remove old widgets, replace with new ones
        self.layout.clear_widgets()
        self.friend_rows = {}
        self.add_friends(friends)

    def change_status(self, userid, status):
        try:
            self.friend_rows[userid].friend.status = status
        except KeyError:
            # no matching userid, probably a chat room, ignore it
            pass

    def add_friend(self, friend):
        if friend.userid in self.friend_rows:
            return

        row = FriendRow(friend)
        self.friend_rows[friend.userid] = row
        self.layout.add_widget(row)

    def add_friends(self, friends):
        for friend in friends:
            self.add_friend(friend)
Example #29
0
class MainScreen(Screen):
    def __init__(self, **kw):
        super(MainScreen, self).__init__(**kw)

        super(MainScreen, self).__init__(**kw)
        box = BoxLayout(orientation='vertical')


        self.items_grid = GridLayout(cols=1, spacing=10, size_hint_y=None, padding=10)
        # Make sure the height is such that there is something to scroll.
        self.items_grid.bind(minimum_height=self.items_grid.setter('height'))
                
        scroll_view = ScrollView(size_hint=(1, 1), size=(Window.width, Window.height))
        scroll_view.add_widget(self.items_grid)

        box.add_widget(scroll_view)

        box.add_widget(Button(text='Добавить элемент;)',
                              on_press=lambda x: set_screen('add_item'),
                              size_hint_y=None, height=dp(80)))
        self.add_widget(box)

    def on_enter(self):  # Будет вызвана в момент открытия экрана

        all_items = gv.db.get_all_items()
        
        for (item_id, item_title, item_time_create) in all_items:
            wrapper = BoxLayout(size_hint_y=None, height=dp(40),)
            btn = Button(
                text=item_title,
                on_press=lambda x, item_id=item_id: self._view_item(item_id)
            )
            btn_del = Button(
                text='DEL', size_hint_x=None, width=dp(70),
                on_press=lambda x, item_id=item_id, wrapper=wrapper: self._del_item(item_id, wrapper)
            )
            wrapper.add_widget(btn_del)
            wrapper.add_widget(btn)
            self.items_grid.add_widget(wrapper)

    def on_leave(self):  # Будет вызвана в момент закрытия экрана
        self.items_grid.clear_widgets()

    def _view_item(self, id_item):
        gv.cur_id_item = id_item
        set_screen('view_item')
    
    def _del_item(self, id_item, wrapper):
        gv.db.delete_item(id_item)
        self.items_grid.remove_widget(wrapper)
class TestApp(App):
    def build(self):
        layout = BoxLayout(orientation='vertical')
        layout.size_hint = (1, 1)
        btn_search = Button(text='Search')
        btn_search.bind(on_press=self.search)
        btn_search.background_color = (32 / 255, 126 / 255, 204 / 255, 1)
        inputAndSearch = BoxLayout(orientation='horizontal')
        inputAndSearch.size_hint = (1.0, 0.1)
        self.text_input = TextInput()
        self.text_input.multiline = False
        self.text_input.bind(on_text_validate=self.search)
        inputAndSearch.add_widget(self.text_input)
        inputAndSearch.add_widget(btn_search)
        results_holder = ScrollView(size_hint=(1, 0.9))
        self.results = GridLayout(cols=1, spacing=10, size_hint_y=None)
        self.results.bind(minimum_height=self.results.setter('height'))

        layout.add_widget(inputAndSearch)
        results_holder.add_widget(self.results)
        layout.add_widget(results_holder)
        return layout

    def search(self, _):
        self.results.clear_widgets()
        a = search(str(self.text_input.text))
        if len(a.ls) == 0:
            self.results.add_widget(Label(text='No resuls found :('))
        for i in a.ls:
            lay = BoxLayout(orientation='horizontal',
                            size_hint_y=None,
                            height=40)
            btn = Button(text='Download')
            btn.url = i['link']
            btn.bind(on_press=self.download)
            btn.background_color = (0.82, 0.82, 0.82, 1)
            d = Label(text=i['name'])
            lay.add_widget(d)
            lay.add_widget(btn)
            self.results.add_widget(lay)  #len(self.results.children)*16))

    def download(self, btn):
        btn.text = 'Downloading...'
        try:
            download(btn.url)
            btn.text = 'Downloaded!'
        except HTTPError:
            btn.text = 'Not valid format :('
        except SystemExit:
            btn.text = 'Not valid format :('
Example #31
0
class HomeRight(GridLayout):
    def __init__(self, main_app, **kwargs):
        super().__init__(**kwargs)
        self.main_app = main_app
        self.cols = 1
        self.page = 0

        self.navigation = GridLayout(cols=4, rows=1, size_hint_y=.05)

        self.navigation.add_widget(Label())

        self.navigation.forward = Button(text="Forward", size_hint_x=.4)
        self.navigation.forward.bind(on_press=lambda e: self.page_forward())
        self.navigation.add_widget(self.navigation.forward)

        self.navigation.back = Button(text="Back", size_hint_x=.4)
        self.navigation.back.bind(on_press=lambda e: self.page_back())
        self.navigation.add_widget(self.navigation.back)

        self.navigation.add_widget(Label())

        self.add_widget(self.navigation)

        self.activity_viewer = GridLayout(cols=1, rows=4, size_hint_y=.95)
        self.add_widget(self.activity_viewer)
        self.show_activities()

    def page_forward(self):
        if self.page > 0:
            self.page -= 1
            print("Forward")
            self.show_activities()

    def page_back(self):
        if self.page * 4 < len(self.main_app.activity_data.activity_list):
            self.page += 1
            print("Back")
            self.show_activities()

    def show_activities(self):
        self.activity_viewer.clear_widgets()
        for i in range(4):
            try:
                self.activity_viewer.add_widget(
                    ActivityWidgets(i + self.page * 4,
                                    self.main_app,
                                    size_hint_y=.25))
            except IndexError:
                print("No activity with index %s".format(i + self.page * 4))
Example #32
0
    def gen_menu(self):
        """
		Creates the base menu which displays all users.
		"""
        self.chatting = None
        self.clear_widgets()
        self.master_layout.clear_widgets()
        self.message_layout.clear_widgets()
        sub_layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
        sub_layout.bind(minimum_height=sub_layout.setter('height'))
        sub_layout.clear_widgets()
        names = []

        for user in self.users:
            names.append(user)

        names.sort()
        op_chat = Button(text='Group Chat: OPERATOR',
                         size_hint_y=None,
                         height=180,
                         color=[0, 0, 0, 1],
                         on_release=functools.partial(self.chat_panel,
                                                      'Operator Group'),
                         background_normal='',
                         background_color=[.5, 1, .5, 1])
        sub_layout.add_widget(op_chat)

        for name in names:
            lab = Button(text=name,
                         size_hint_y=None,
                         height=100,
                         color=[1, 1, 1, 1],
                         on_release=functools.partial(self.chat_panel, name),
                         background_normal='',
                         background_color=[0, .3, .3, 1])
            sub_layout.add_widget(lab)

        refresh = Button(text="Refresh Users",
                         size_hint_y=None,
                         on_release=lambda x: self.get_users(),
                         height=180,
                         color=[0, 0, 0, 1],
                         background_normal='',
                         background_color=[0, 1, 0, 1])
        self.message_layout.add_widget(refresh)
        self.message_layout.add_widget(sub_layout)
        self.master_layout.add_widget(self.message_layout)
        self.add_widget(self.master_layout)
Example #33
0
def update_list(layout: GridLayout, itemlist: ty.List[Item]):
    layout.clear_widgets()
    try:
        rpr.Project()
    except (rpr.errors.DisabledDistAPIError, AttributeError):
        print('cannot connect')
        return
    with rpr.inside_reaper():
        for item in itemlist:
            btn = Button(
                text=item.name, size_hint_y=None, height=Window.height / 10
            )
            btn.bind(
                on_press=lambda instance, time=item.time:
                on_track(time, instance)
            )
            layout.add_widget(btn)
Example #34
0
class TstApp(App, GridLayout):
    def __init__(self, **kwargs):
        super(TstApp, self).__init__(**kwargs)
        self.layout = GridLayout(cols=1, padding=100)
        self.add_widget(self.layout)
        self.tsts = self.get_tst_modules(".")  # []
        # self.tsts.append(run_tst_card)
        # self.tsts.append(run_tst_board)
        # self.tsts.append(run_tst_score_board)
        # self.tsts.append(run_tst_controller)
        Clock.schedule_once(lambda dt: self.tst_scheduler(), 3)

    def build(self):
        return self

    def get_tst_modules(self, path):
        tst_files = []
        sys.path.insert(1, os.path.join(sys.path[0], 'tests'))
        sys.path.insert(1, os.path.join(sys.path[0], '..'))

        for root, dirs, files in os.walk(path):
            tst_dir = re.search(r"tests$", r"{}".format(root))
            if tst_dir:
                for file in files:
                    if 'tst_' in file:
                        tst_files.append(
                            file[:-3])  # os.path.join(root, file))
                        print("get_tst_modules", tst_files[-1])

        return list(map(__import__, tst_files))

    def tst_scheduler(self):
        tst = self.tsts.pop(0)
        print("tst_scheduler", tst.__name__)
        self.layout.clear_widgets()
        tst.run(self.layout, self.tst_finished)

    def tst_finished(self):
        if self.tsts:
            Clock.schedule_once(lambda dt: self.tst_scheduler(), 3)
        else:
            print("tst_finished", "all done")
            self.stop()
Example #35
0
class SuccScreen(Screen):
    def __init__(self, **kw):
        super(SuccScreen, self).__init__(**kw)

    def on_enter(self):  # Будет вызвана в момент открытия экрана
        global bbb
        self.layout = GridLayout(cols=bbb)
        self.layout.bind(minimum_height=self.layout.setter('height'))

        root = RecycleView(size_hint=(1, None), size=(Window.width,
                                                      Window.height))
        root.add_widget(self.layout)
        self.add_widget(root)

        for i in range(aaaa):
            btn = Button(text="succ", on_press=lambda x: succc())
            self.layout.add_widget(btn)

    def on_leave(self):  # Будет вызвана в момент закрытия экрана
        self.layout.clear_widgets()  # очищаем список
Example #36
0
class PaperCollection(Screen):
    def __init__(self, **kw):
        super(PaperCollection, self).__init__(**kw)

    def on_enter(self):  # Будет вызвана в момент открытия экрана

        self.layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
        self.layout.bind(minimum_height=self.layout.setter('height'))
        back_button = Button(text='< Назад к выбору коллекции',
                             on_press=lambda x: set_screen('start_menu'),
                             size_hint_y=None,
                             height=dp(40))
        self.layout.add_widget(back_button)
        root = RecycleView(size_hint=(1, None),
                           size=(Window.width, Window.height))
        root.add_widget(self.layout)
        self.add_widget(root)

    def on_leave(self):  # Будет вызвана в момент закрытия экрана

        self.layout.clear_widgets()  # очищаем список
Example #37
0
class MultilingualApp(App):
    def build(self):
        self.set_language('en_US')
        self.root = GridLayout(cols = 1)
        self.root.add_widget(Multilingual())
        return self.root

        #self.root.myfunction('blah')
      
    def set_language(self,selectedLanguage):
        self.t = gettext.translation('multilingual', languagePath, languages=[selectedLanguage], fallback=True)
        _ = self.t.ugettext #The 'u' in 'ugettext' is for Unicode - use this to keep Unicode from breaking the app
        #self.root.greeting = _('Hello!')
 
    def get_text(self, *args):
        return self.t.ugettext(*args)
    
    def build_config(self, config):
        config.add_section('localization')
        config.set('localization', 'language', 'en_US')
    
    def build_settings(self, settings):
        settings.add_json_panel('Multilingual', self.config, data='''[
            { "type": "title", "title": "Language Settings" },
            { "type": "options", "title": "Language",
              "desc": "Choose which language to translate the text of this app into",
              "section": "localization", "key": "language",
              "options": ["en_US", "de", "fr", "es"]}
        ]''')
 
    def on_config_change(self, config, section, key, value):
        if config is not self.config:
            return
        token = (section, key)
        if token == ('localization', 'language'):
            self.set_language(value)
            self.root.clear_widgets()
            self.root.remove_widget(Multilingual())
            self.root.add_widget(Multilingual())
        print "Language is now", value
Example #38
0
class ClientServerChoice(App):
    def build(self):
        self.layout = GridLayout(cols=2, row_force_default=True, row_default_height=150)
        button1 = Button(text='Start client', font_size=14)
        button1.bind(on_press=run_client)
        self.layout.add_widget(button1)
        button2 = Button(text='Start server', font_size=14)
        button2.bind(on_press=run_server)
        self.layout.add_widget(button2)
        #TO KEEP GARBAGE COLLECTOR OFF OUR LAYOUT
        layout = self.layout
        print '-------------build---------------'
        print layout
        return self.layout

    def switch_UI(self):
        print '-------------test--------------'
        print self.layout
        self.layout.clear_widgets()
        print self.layout
        button1 = Button(text='Send sound', font_size=14)
        button1.bind(on_press=send_sound)
        button2 = Button(text='Exit network', font_size=14)
        button2.bind(on_press=close_network)
        self.layout.add_widget(button1)
        self.layout.add_widget(button2)
        
    def original_UI(self):
        self.layout.clear_widgets()
        button1 = Button(text='Start client', font_size=14)
        button1.bind(on_press=run_client)
        self.layout.add_widget(button1)
        button2 = Button(text='Start server', font_size=14)
        button2.bind(on_press=run_server)
        self.layout.add_widget(button2)
        #TO KEEP GARBAGE COLLECTOR OFF OUR LAYOUT
        layout = self.layout
Example #39
0
class ContactTab(TabbedPanelItem):
    logic = ObjectProperty(None)

    def __init__(self,**kargs):
        super(ContactTab,self).__init__(**kargs)
        self.logic = App.get_running_app().logic
        self.build_interface()

    def build_interface(self):
        self.layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
        self.layout.clear_widgets()
        self.layout.bind(minimum_height=self.layout.setter('height'))
        for contact in self.logic.contacts:
            # dont add yourself to contact-list!
            if str(contact) == self.logic.name:
                continue
            btn = Button(text = contact, size_hint_y=None, height=40,
                                    on_press = self.logic.btn_call_up)
            self.layout.add_widget(btn)
        self.content = ScrollView()
        self.content.add_widget(self.layout)

    def contact_tab_update(self):
        self.build_interface()
Example #40
0
    def __init__(self, **kwargs):
        super(ScoreFetchGUI, self).__init__(**kwargs)
        scoreLayout = GridLayout(cols=3, rows=4, size_hint=(0.7, 1), pos=(210, 0))
        self.add_widget(scoreLayout)
        dlPodBtn = Button(text="Download Podcast", size_hint=(0.25, 0.15), pos=(20, 100))
        sfBtn = Button(text="ScoreFetch!", size_hint=(0.25, 0.15), pos=(20, 150))
        feedBtn = Button(text="Watch Feed", size_hint=(0.25, 0.15), pos=(20, 50))
        feedTeamInput = TextInput(text="team", size_hint=(0.25, 0.13), pos=(20, 10), focus=True, multiline=False)
        wimg = Image(source="/home/joe/Pictures/sfbanner.png", pos=(0, 0))
        # enterTeamLbl = Label(
        # text='Enter Team Name:',
        # pos=(-215, -70))
        leagueToggleNHL = ToggleButton(text="NHL", group="league", size_hint=(0.1, 0.1), pos=(27, 200), state="down")
        leagueToggleNBA = ToggleButton(text="NBA", group="league", size_hint=(0.1, 0.1), pos=(100, 200))
        dlPodBtn.bind(on_release=whichPodCallback)
        leagueToggleNBA.bind(on_press=choiceCallbackNBA)
        leagueToggleNHL.bind(on_press=choiceCallbackNHL)
        feedTeamInput.bind(text=on_text)
        feedBtn.bind(on_release=showFeedCallback)
        self.add_widget(wimg)
        # self.add_widget(enterTeamLbl)
        self.add_widget(leagueToggleNHL)
        self.add_widget(leagueToggleNBA)
        self.add_widget(dlPodBtn)
        self.add_widget(sfBtn)
        self.add_widget(feedBtn)
        self.add_widget(feedTeamInput)

        url = "http://scores.nbcsports.msnbc.com/ticker/data/gamesMSNBC.\
js.asp?jsonp=true&sport=%s&period=%d"
        yymmdd = int(datetime.datetime.now(pytz.timezone("US/Mountain")).strftime("%Y%m%d"))
        scoreLayout.clear_widgets()

        def getScores(instance):
            try:
                scoreLayout.clear_widgets()
                f = urllib2.urlopen(url % (choice, yymmdd))
                jsonp = f.read()
                f.close()
                jsonStr = jsonp.replace("shsMSNBCTicker.loadGamesData(", "").replace(");", "")
                jsonParsed = json.loads(jsonStr)
                for gameStr in jsonParsed.get("games", []):
                    gameTree = ET.XML(gameStr)
                    visitingTree = gameTree.find("visiting-team")
                    homeTree = gameTree.find("home-team")
                    gameSTree = gameTree.find("gamestate")
                    home = homeTree.get("nickname")
                    away = visitingTree.get("nickname")
                    homeScore = homeTree.get("score")
                    visitScore = visitingTree.get("score")
                    per = gameSTree.get("display_status2")
                    clock = gameSTree.get("display_status1")
                    os.environ["TZ"] = "US/Mountain"
                    del os.environ["TZ"]
                    playingLabel = Label(
                        valign="top",
                        halign="left",
                        text=visitScore + " " + away + " " + per + "\n" + homeScore + " " + home + " " + clock,
                        text_size=(200, None),
                    )
                    scoreLayout.add_widget(playingLabel)

            except Exception, e:
                print e
Example #41
0
class LoadDynamic(Empty):

    def __init__(self, **kwargs):

        super(LoadDynamic, self).__init__(kwargs=kwargs)

        self.path_modules_and_xml = os.path.dirname(__file__) .replace\
            ('/gui/data_processing_panel/alternatives','/controller/procesing/dynamic_modules')

        self.function_dictionary = self.load_xml()

        self.add_function = Button(text="add new")
        self.add_function.bind(on_press=self.create_function)
        self.import_function = Button(text='import function')
        self.import_function.bind(on_press=self.copy_function)

        top_layot = BoxLayout(orientation='horizontal',  size_hint=(1,None), size=(1,30))
        top_layot.add_widget(self.import_function)
        top_layot.add_widget(self.add_function)

        ####
        self.func_container = GridLayout(cols=1, spacing=0, size_hint_y=None)#row_default_height=30)
        self.func_container.bind(minimum_height=self.func_container.setter('height'))

        scroll_root = ScrollView(size_hint=(1,1),  size=(1, 125))
        scroll_root.add_widget(self.func_container)

        ###

        padding_layout = BoxLayout(size_hint=(1,1))
        big_one = BoxLayout(orientation='vertical')
        big_one.add_widget(top_layot)
        big_one.add_widget(scroll_root)
        #big_one.add_widget(padding_layout)

        self.add_widget(big_one)

        self.modules_function_loaded = {}
        self.free_run_variable_dictionary = {}

    def load_xml(self):
        FILE = open(self.path_modules_and_xml + "/setup.xml", 'r')
        modules = xmlfromstring(FILE.read())

        dic_return = {}

        for module in modules._children:
            module_name = module.attrib['name']
            module_dict = {}
            for functions in module._children:
                function_name = functions.attrib['name']
                args_name = []
                for args in functions._children:
                    args_name.append(args.attrib['name'])
                module_dict[function_name] = args_name
            dic_return[module_name] = module_dict

        return dic_return

    def create_function(self, instance):
        function_list = self.get_function_list()
        threading.Thread(target=self.create_function_thread, args=(function_list,)).start()

    def create_function_thread(self, function_list):
        content = FunctionSelector( function_list)

        a_popup = Popup(title='Choose Bof', auto_dismiss=False, content=content, size_hint=(None, None), size=(400,400))
        content.set_popup(a_popup)
        a_popup.open()

        while content.continues:
            pass

        keys = content.choosen_name.split('.')
        if content.is_default():
            return

        new_widget = FunctionGui( keys[0],keys[1],self.function_dictionary[keys[0]][keys[1]], self.delete_one_function)
        new_widget.update_free_run_dictionary(self.free_run_variable_dictionary)

        self.func_container.add_widget(new_widget)

        if not new_widget.module_name in self.modules_function_loaded:
            self.modules_function_loaded[new_widget.module_name] = {}

        self.modules_function_loaded[new_widget.module_name][new_widget.function_name + new_widget.special_name] = new_widget
        #self.func_container.add_widget(Button(text=content.choosen_name + ' ' + str(self.function_dictionary[keys[0]][keys[1]]),size_hint=(1,None), size=(1,30)))

    def delete_one_function(self, module_name, function_name):
        print self.modules_function_loaded

        module_dic = self.modules_function_loaded[module_name]
        del_function = module_dic[function_name]
        del module_dic[function_name]

        self.func_container.remove_widget(del_function)

        print self.modules_function_loaded

    def get_function_list(self):
        function_list_return = []

        for module in self.function_dictionary:
            module_dic = self.function_dictionary[module]

            for function in module_dic:
                function_list_return.append(module + '.' + function)

        return function_list_return

    def copy_function(self, instance):
        content = BofFileChooserIconView(return_selection_path=self.copy_function_copy_file )
        a_popup = Popup(title='Choose Bof', auto_dismiss=False, content=content, size_hint=(None, None), size=(400,400))
        content.set_popup(a_popup)
        a_popup.open()

    def copy_function_copy_file(self, path):
        module_name = path.split("/")[-1]
        module_name = str(module_name.replace('.py',''))
        print 'name',module_name, type(module_name)

        command = "cp %s %s" %(path, self.path_modules_and_xml)

        print command
        os.system(command)
        try:
            dynamic_module = __import__('omt.controller.procesing.dynamic_modules' , globals(), locals(), [module_name,],-1)
            dynamic_module = getattr(dynamic_module, module_name)
            posible_fucntion_list = dir(dynamic_module)
        except Exception as e:
            Popup(title='Import Error',content=Label(text=e.msg + '\nline ' + str(e.lineno)), size_hint=(None,None), size=(500,300)).open()
            return

        actual_functions = []
        #extract the created function
        for a_funtion in posible_fucntion_list:
            function_aux = getattr(dynamic_module,a_funtion)
            if types.FunctionType == type(function_aux) and a_funtion.replace('__','',1) == a_funtion:
                actual_functions.append(a_funtion)

        print actual_functions

        module_function_list = {}
        for a_function in actual_functions:

            funct_reference = getattr(dynamic_module, a_function)
            #function_dic['args_name'] = funct_reference.__code__.co_varnames
            module_function_list[a_function] = funct_reference.__code__.co_varnames[:funct_reference.__code__.co_argcount]
            #module_function_list[a_function + "_instance"] = funct_reference

        if not module_name in self.function_dictionary:
            print 'add info to dic'
            self.function_dictionary[module_name] = module_function_list
        else:
            Popup(title='Module Error', content=Label(text="Repeated module name,\nplease change yours")\
                  , size_hint=(None, None), size=(200,200)).open()
            return

        print self.function_dictionary

        self.save_xml()

    def save_xml(self, ):
        module_dict_xml = Element('dynamic_modules')
        comment = Comment('Modules info')
        module_dict_xml.append(comment)

        for aKey in self.function_dictionary:
            module_dic = self.function_dictionary[aKey]

            module_xml = SubElement(module_dict_xml,'module',attrib={'name':aKey})

            for aFunctionKey in module_dic:
                aFunction = module_dic[aFunctionKey]
                function_xml = SubElement(module_xml,'function', name=aFunctionKey)

                for args in aFunction:
                    arg_xml = SubElement(function_xml,'arg', name=args)

        rough_string = xmltostring(module_dict_xml, 'utf-8')
        reparsed = minidom.parseString(rough_string)

        string_xml = reparsed.toprettyxml(indent="  ")

        FILE = open(self.path_modules_and_xml + "/setup.xml", "w")
        FILE.write(string_xml)
        FILE.close()

    def update_free_run_dictionary(self, data_dic):
        self.free_run_variable_dictionary = data_dic
        for m_key in self.modules_function_loaded:
            module_dic = self.modules_function_loaded[m_key]
            for f_key in module_dic:
                function = module_dic[f_key]
                function.update_free_run_dictionary(data_dic)

    def get_source_config(self):
        return_dic = {}
        for element in self.modules_function_loaded:
            module = self.modules_function_loaded[element]
            for key in module:
                widget = module[key]
                return_dic[widget.special_name] = widget.get_source_config()
        return return_dic

    def sava_config_dictionary(self):
        return_dic = {}

        for element in self.modules_function_loaded:
            module = self.modules_function_loaded[element]
            for key in module:
                widget = module[key]
                dic = widget.get_source_config()
                return_dic[dic['function_name_special']] = dic

        return  return_dic

    def set_configuration(self, dic):

        self.modules_function_loaded = {}
        self.func_container.clear_widgets()
        for func in dic:

            func_dic = dic[func]
            func_module = func_dic['module_name']
            func_name = func_dic['function_name']
            new_widget = FunctionGui( func_module,func_name,self.function_dictionary[func_module][func_name], self.delete_one_function)
            new_widget.update_free_run_dictionary(self.free_run_variable_dictionary)

            self.func_container.add_widget(new_widget)

            if not new_widget.module_name in self.modules_function_loaded:
                self.modules_function_loaded[new_widget.module_name] = {}

            self.modules_function_loaded[new_widget.module_name][new_widget.function_name + new_widget.special_name] = new_widget

            new_widget.set_configuration(func_dic)
Example #42
0
class ROACH(Empty):

    def __init__(self, **kwargs):

        super(ROACH, self).__init__(kwargs=kwargs)

        self.config_manager = LoadSaveConfig(os.path.dirname(os.path.realpath(__file__)) + '/roach_configurations')
        big_one = BoxLayout(orientation='vertical')

        self.reg_array = {}
        self.reg_cont = 0

        self.bram_array = {}
        self.bram_cont = 0

        #self.snapshot_array = {}
        #self.snapshot_cont = 0

        self.prog_dev = False
        self.bof_path = ''

        self.sources = []
        self.function = []

        # reg layout
        roach_connection_info = BoxLayout(orientation='horizontal',  size_hint=(1,None), size=(1,30))
        roach_register = BoxLayout(orientation='horizontal', size_hint=(1,None), size=(1,40))

        ip_label = Label(text='IP :')
        port_label = Label(text='Port :')

        self.ip = TextInput(multiline=False)
        self.port = TextInput(multiline=False, Text='7417')

        roach_connection_info.add_widget(ip_label)
        roach_connection_info.add_widget(self.ip)
        roach_connection_info.add_widget(port_label)
        roach_connection_info.add_widget(self.port)

        clear_button = Button(text='clear', size_hint=(0.33,1))
        save_button = Button(text='save',  size_hint=(0.33,1))
        clear_button.bind(on_press=self.clear_button)
        save_button.bind(on_press=self.button_save_all)
        self.program_button = ToggleButton(text='program',  size_hint=(0.33,1))

        buttons_layout = BoxLayout(orientation='horizontal', size_hint=(1,None), size=(1,30))
        buttons_layout.add_widget(clear_button)
        buttons_layout.add_widget(save_button)
        buttons_layout.add_widget(self.program_button)

        new_reg_label = Label(text='Initial Values', size_hint=(0.6,None), height=40)
        new_reg = Button(text='new reg', size_hint=(0.4,None), height=40)
        new_reg.bind(on_press=self.add_registers)

        roach_register.add_widget(new_reg_label)
        roach_register.add_widget(new_reg)
        ##### Regiter container
        self.reg_container = GridLayout(cols=1, spacing=0, size_hint_y=None)#row_default_height=30)
        self.reg_container.bind(minimum_height=self.reg_container.setter('height'))

        scroll_root = ScrollView(size_hint=(1,1),  size=(1, 125))
        scroll_root.add_widget(self.reg_container)
        ####

        free_running_label_layout = BoxLayout(orientation='horizontal', size_hint=(1,None), size=(1,30))
        add_free_running_label = Label(text="Free Running", size_hint=(0.45,1))
        free_running_label_layout.add_widget(add_free_running_label)

        free_running = BoxLayout(orientation='horizontal', size_hint=(1,None), size=(1,30))
        add_free_running_bram = Button(text = 'New BRAM', size_hint=(0.30,1))
        add_free_running_reg = Button(text = 'New Reg', size_hint=(0.25,1))
        add_free_running_snapshot = Button(text = 'SnapShot', size_hint=(0.25,1))
        add_free_running_bram.bind(on_press=self.add_free_running)
        add_free_running_reg.bind(on_press=self.add_register_free_running)
        add_free_running_snapshot.bind(on_press=self.add_snapshot_free_running)

        free_running.add_widget(add_free_running_bram)
        free_running.add_widget(add_free_running_reg)
        free_running.add_widget(add_free_running_snapshot)

        #### free run container
        self.free_run_container = GridLayout(cols=1, spacing = 3,size_hint=(1,None), size=(1,30))
        self.free_run_container.bind(minimum_height=self.free_run_container.setter('height'))

        scroll_root_free_run = ScrollView(size_hint=(1,1), size=(1,195), scroll_type=['bars'])
        scroll_root_free_run.add_widget(self.free_run_container)
        scroll_root_free_run.bar_width = 10
        ####

        size_ = 30
        name_config = Button(text='Name',size_hint=(0.25,None), height=size_)
        self.name_config_input = TextInput(size_hint=(0.5,None), height=size_)
        buton_bof_file = Button(text='Add bof',size_hint=(0.25,None), height=size_)

        print os.path.dirname(os.path.realpath(__file__)) + '/roach_configurations'


        name_config.bind(on_press=self.open_look_directory)


        fc = BofFileChooserIconView(self.set_bof_path)
        self.file_choose_popup = Popup(title='Choose Bof', auto_dismiss=False, content=fc,\
                                       size_hint=(None, None), size=(400,400))
        fc.set_popup(self.file_choose_popup)
        buton_bof_file.bind(on_press=self.file_choose_popup.open)

        name = BoxLayout(orientation='horizontal', size_hint=(1,None), size=(1,30))
        name.add_widget(name_config)
        name.add_widget(self.name_config_input)
        name.add_widget(buton_bof_file)

        ## store or plot

        big_one.add_widget(name)
        big_one.add_widget(roach_connection_info)
        big_one.add_widget(buttons_layout)
        big_one.add_widget(roach_register)
        big_one.add_widget(scroll_root)
        big_one.add_widget(free_running_label_layout)
        big_one.add_widget(free_running)
        big_one.add_widget(scroll_root_free_run)

        padding_layout = BoxLayout()
        #big_one.add_widget(padding_layout)

        self.add_widget(big_one)
        self.do_extraction = None

    def open_look_directory(self, instance):
        fc_conf = BofFileChooserIconView(self.load_data, path=os.path.dirname(os.path.realpath(__file__)) + '/roach_configurations' , filter=['*.pkl'])
        self.file_roch_popup = Popup(title='Choose Configuration', auto_dismiss=False, content=fc_conf,\
                                       size_hint=(None, None), size=(400,400))
        fc_conf.set_popup(self.file_roch_popup)
        self.file_roch_popup.open()

    def add_register_free_running(self, instance):
        self.load_register_free_running('','')

    def load_register_free_running(self, value_, name_):
        bram = self.create_registers(value_, name_, self.free_run_container, self.remove_from_widget_list_free_run, \
                                     str(self.bram_cont))

        self.bram_array[str(self.bram_cont)] = bram
        bram.set_extraction_function(self.do_extraction)
        self.bram_cont += 1

    def add_registers(self, instance):
        self.load_registers("","", self.reg_container)

    def load_registers(self, values_, name_, where_load_):
        reg_val = self.create_registers(values_, name_, where_load_, self.remove_from_widget_list_config, str(self.reg_cont))

        self.reg_array[str(self.reg_cont)] = reg_val
        self.reg_cont += 1

    def create_registers(self, values_, name_, where_load_, remove_function_, cont_key_):

        size_ = 30
        data = BoxLayout(orientation='horizontal',size_hint=(1, None), size=(1,size_))

        label_name = Label(text='Name', size_hint=(0.225,None), height=size_)
        value_name = TextInput( size_hint=(0.225,None), height=size_)
        label_val = Label(text='Value', size_hint=(0.225,None), height=size_)
        value_val = TextInput( size_hint=(0.225,None), height=size_)
        delate = Button(text='-', size_hint=(0.1,None), height=size_)

        delate.bind(on_press=lambda instant:\
                    remove_function_(data, cont_key_))# where_load_.remove_widget(data))


        data.add_widget(label_name)
        data.add_widget(value_name)
        data.add_widget(label_val)
        data.add_widget(value_val)
        data.add_widget(delate)

        value_name._set_text(name_)
        value_val._set_text(values_)

        where_load_.add_widget(data)

        return Register(value_name, value_val)

    def add_free_running(self, instance):
        self.load_free_running('i', '', [], '','')

    def is_active(self):
        return True

    def activate_extract(self, f):
        self.do_extraction = f

    def get_config(self):
        dic_return = {}

        regs = []
        keys = self.reg_array.keys()
        keys.sort()

        for a_reg in keys:
            aux_data = self.reg_array[a_reg]
            reg_name = aux_data.get_name()
            reg_val = aux_data.get_value()

            regs.append((reg_name, reg_val))

        dic_return['reg'] = regs

        brams = []

        keys_ = self.bram_array.keys()
        keys_.sort()
        for bram in keys_:
            brams.append(self.bram_array[bram].info_dictionary())

        dic_return['bram'] = brams

        dic_return['ip'] = self.ip._get_text()
        dic_return['port'] = self.port._get_text()

        dic_return['bof_path'] = self.bof_path
        dic_return['name'] = self.name_config_input._get_text()

        dic_return['progdev'] = True if self.program_button.state == 'down' else False

        source_dic_config = {}
        for a_source in self.sources:
            source_dic_config.update( a_source.save_config_dictionary())
        dic_return['sources'] = source_dic_config

        function_dic_config = {}
        for a_function in self.function:
            function_dic_config.update(a_function.sava_config_dictionary())
        dic_return['functions'] = function_dic_config

        dic_return['wich'] = self.which_roach()

        # this line saves the dictionary to file with pikle
        self.config_manager.store_dictionary(dic_return)

        dic_return['instance'] = self.get_controller_fpga_insctance()

        return dic_return

    def get_controller_fpga_insctance(self):
        pass

    def set_bof_path(self, path):

        if len(self.name_config_input.text) <1:
            Popup(content=Label(text='Enter Name'), size_hint=(None,None),size=(200,100)).open()
            return

        self.bof_path = self.config_manager.copy_bof_to_folder(path, self.name_config_input._get_text())
        self.program_button.state = "down"

    def load_data(self, path):
        self.clean_all()
        dic = self.config_manager.load_dictionary(path)

        try:
            if dic['wich'] != self.which_roach():
                return
        except:
            pass

        regs = dic['reg']

        for a_reg in regs:
            self.load_registers(a_reg[1], a_reg[0], self.reg_container)

        brams = dic['bram']

        for a_bram in brams:
            if a_bram['is_bram']:
                try:
                    self.load_free_running(a_bram['data_type'],a_bram['size'],a_bram['bram_names'],a_bram['acc_len_reg'], \
                                       a_bram['array_id'], a_bram['store'], a_bram['plot'])
                except:
                    self.load_free_running(a_bram['data_type'],a_bram['size'],a_bram['bram_names'],a_bram['acc_len_reg'], \
                                       a_bram['array_id'])

            else:
                if 'snap' in a_bram:
                    self.load_snapshot_free_running(a_bram['name'])
                else:
                    self.load_register_free_running(a_bram['reg_value'], a_bram['reg_name'])

        self.ip._set_text(dic['ip'])
        self.port._set_text(dic['port'])

        self.program_button.state = 'down' if dic['progdev'] else 'normal'

        self.bof_path = os.path.dirname(os.path.realpath(__file__)) + \
                        '/roach_configurations/' + dic['name'] + '/' + dic['name'] + '.bof'
        self.name_config_input._set_text(dic['name'])

        try:
            for a_source in self.sources:
                a_source.set_configuration(dic['sources'])


        except Exception as e:
            pass

        for a_function in self.function:
                a_function.set_configuration(dic['functions'])

        self.do_extraction()

    def load_free_running(self, a_data_type, array_size_, real_imag_list_,
                          acc_len_reg_name_, array_label_, store_ = False, plot_ = False):
        size_ = 30
        data = BoxLayout(orientation='vertical',size_hint=(1, None), size=(1,8*size_))

        # plot_label = Label(text='Plot data:', size_hint=(0.4,1))
        plot_toogle = ToggleButton(text='Plot Data', size_hint=(0.5,1))
        store_data = ToggleButton(text='Store Data', size_hint=(0.5,1))
        handle_data = BoxLayout(orientation='horizontal', size_hint=(1, None), size=(1, 30))
        handle_data.add_widget(plot_toogle)
        handle_data.add_widget(store_data)

        data_type_label = Label(text='Tipo de Dato', size_hint=(0.4,None), height=size_)
        data_type_spinner = Spinner(
            # default value shown
            text=a_data_type,
            # available values
            values=['c', 'b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q', 'f', 'd'],
            # just for positioning in our example
            size_hint=(0.3, None),
            size = (1, size_)
        )
        delate_label = Label(text='Quitar', size_hint=(0.2,None), height=size_)
        delate_me = Button(text='-', size_hint=(0.1,None), height=size_)
        str_cont = str(self.bram_cont)
        delate_me.bind(on_press=lambda instance:self.remove_from_widget_list_free_run(data, str_cont))

        id_label = Label(text='array name',size_hint=(0.45, None), height=size_)
        id_input = TextInput(size_hint=(0.45, None), height=size_)

        size_label = Label(text='size', size_hint=(0.45, None), height=size_)
        size_input = TextInput(size_hint=(0.45, None), height=size_)

        add_new_array_to_merge = Button(text='+',size_hint=(None, None), height=size_, wide = 3*size_)

        real_imag = GridLayout(cols=1, spacing = 3,size_hint=(1, None), size=(1,60))
        real_imag.bind(minimum_height=real_imag.setter('height'))

        scroll_real_imag = ScrollView(size_hint=(0.8,None), size=(1,2*size_))
        scroll_real_imag.add_widget(real_imag)

        acc_len_reg_name_label = Label(text='acc len reg_name',size_hint=(0.5,None), height=size_)
        acc_len_reg_name_input = TextInput(size_hint=(0.5, None), height=size_)

        data_type = BoxLayout(orientation='horizontal',size_hint=(1, None), size=(1,size_))
        data_type.add_widget(data_type_label)
        data_type.add_widget(data_type_spinner)
        data_type.add_widget(delate_label)
        data_type.add_widget(delate_me)

        data_id = BoxLayout(orientation='horizontal',size_hint=(1, None), size=(1,size_))
        data_id.add_widget(id_label)
        data_id.add_widget(id_input)

        data_size = BoxLayout(orientation='horizontal',size_hint=(1, None), size=(1,size_))
        data_size.add_widget(size_label)
        data_size.add_widget(size_input)

        data_add_merge_data = BoxLayout(orientation='horizontal',size_hint=(1, None), size=(1,size_))
        data_add_merge_data.add_widget(add_new_array_to_merge)

        data_name = BoxLayout(orientation='horizontal',size_hint=(1, None), size=(1,2*size_))
        data_name.add_widget(scroll_real_imag)

        data_acc_len_reg = BoxLayout(orientation='horizontal',size_hint=(1, None), size=(1,size_))
        data_acc_len_reg.add_widget(acc_len_reg_name_label)
        data_acc_len_reg.add_widget(acc_len_reg_name_input)

        data.add_widget(handle_data)
        data.add_widget(data_type)
        data.add_widget(data_id)
        data.add_widget(data_size)
        data.add_widget(data_add_merge_data)
        data.add_widget(data_name)
        data.add_widget(data_acc_len_reg)

        bram = BRAMArray( size_input, acc_len_reg_name_input,real_imag, id_input, data_type_spinner, store_data
                          , plot_toogle)
        bram.set_extraction_function(self.do_extraction)

        add_new_array_to_merge.bind(on_press=lambda instance: bram.add_real_imag_widget())

        self.bram_array[str(self.bram_cont)] = bram
        self.bram_cont += 1
        self.free_run_container.add_widget(data)

        size_input._set_text(array_size_)
        acc_len_reg_name_input._set_text(acc_len_reg_name_)
        id_input._set_text(array_label_)

        store_data.state = 'down' if store_ else 'normal'
        plot_toogle.state = 'down' if plot_ else 'normal'

        for real_imag_pair in real_imag_list_:
            bram.load_real_imag_widget(real_imag_pair[0], real_imag_pair[1])

    def remove_from_widget_list_free_run(self, widget_, list_cont_val_):
        self.free_run_container.remove_widget(widget_)
        del self.bram_array[list_cont_val_]

    def remove_from_widget_list_config(self, widget_, list_cont_val_):
        self.reg_container.remove_widget(widget_)
        del self.reg_array[list_cont_val_]

    def clean_all(self):
        self.free_run_container.clear_widgets()
        self.reg_container.clear_widgets()

        self.bram_array = {}
        self.reg_array = {}

        self.bram_cont = 0
        self.reg_cont = 0

        self.name_config_input.text = ''
        self.bof_path = ''
        self.ip.text = ''
        self.port.text = ''

        self.program_button.state = 'normal'

    def clear_button(self, inatance):
        self.clean_all()

    def button_save_all(self, instance):
        self.get_config()

    def pass_source(self, sources_):
        self.sources = sources_

    def pass_functions(self, functions_):
        self.function = functions_

    def which_roach(self):
        pass

    def add_snapshot_free_running(self, instance):
        self.load_snapshot_free_running('')

    def load_snapshot_free_running(self,snapshot_name_):
        size_ = 30
        data = BoxLayout(orientation='horizontal',size_hint=(1, None), size=(1,size_))

        snap_name_label = Label(text='Snap Name',size_hint=(0.4,None), height=size_)
        snap_name_value = TextInput(size_hint=(0.4,None), height=size_)
        snap_name_value.text = snapshot_name_

        delate_me = Button(text='-',size_hint=(0.1,None), height=size_)
        str_cont = str(self.bram_cont)
        delate_me.bind(on_press=lambda instance:\
            self.remove_from_widget_list_free_run(data, str_cont))

        snap = SnapShot(snap_name_value)
        snap.set_extraction_function(self.do_extraction)

        data.add_widget(snap_name_label)
        data.add_widget(snap_name_value)
        data.add_widget(delate_me)

        self.free_run_container.add_widget(data)

        self.bram_array[str(self.bram_cont)] = snap
        self.bram_cont += 1
Example #43
0
class SelectionDate(Popup):
    def __init__(self, *args, **kwargs):
        super(SelectionDate, self).__init__(*args, **kwargs)	
        self.bind(on_dismiss=self.on_dismiss)
        
        self.callback = kwargs.pop("callback", None)
        self.selectionDate = kwargs.pop("date", datetime.date.today())
        
        self.selectionMois = self.selectionDate.month
        self.selectionAnnee = self.selectionDate.year
    
        self.listeJours = [ 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam', 'Dim' ]
        self.listeMois = [ 'Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre' ]
        
        self.box_base = BoxLayout(orientation="vertical", padding=10)
        
        # Affichage des commandes de navigation
        box_navigation = BoxLayout(orientation="horizontal", size_hint=(1, None), height=40)
        
        b = Button(text="<", size_hint=(0.2, 1))
        box_navigation.add_widget(b) 
        b.bind(on_release=self.on_bouton_navigation)
        
        self.ctrl_titre = Label(text="", size_hint=(1, 1), markup=True, font_size=22, color=get_color_from_hex("30a3cc"))
        box_navigation.add_widget(self.ctrl_titre)         

        b = Button(text=">", size_hint=(0.2, 1))
        box_navigation.add_widget(b) 
        b.bind(on_release=self.on_bouton_navigation)
        
        self.box_base.add_widget(box_navigation) 
        
        # Affichage des jours        
        self.box_grille = GridLayout(cols=7)  
        self.RemplissageJours()
        self.box_base.add_widget(self.box_grille) 
        
        self.add_widget(self.box_base) 

    def RemplissageJours(self):
        calendrier = calendar.monthcalendar(self.selectionAnnee, self.selectionMois)
        
        for d in self.listeJours :
            b = Label(text=d, markup=True)
            self.box_grille.add_widget(b)
         
        for wk in range(len(calendrier)):
            for d in range(0,7):    
                dateOfWeek = calendrier[wk][d]
                if not dateOfWeek == 0:
                    date = datetime.date(self.selectionAnnee, self.selectionMois, dateOfWeek)
                    b = Button(text=str(dateOfWeek))
                    if date == self.selectionDate :
                        b.background_color = get_color_from_hex("30a3cc")
                        b.background_normal = ""
                    if date == datetime.date.today() :
                        b.color = (1, 0, 0, 1)
                    b.bind(on_release = self.on_release)
                else:
                    b = Label(text='')
                self.box_grille.add_widget(b)   
        
        # Mise à jour du titre
        self.ctrl_titre.text = "[b]" + self.listeMois[self.selectionMois-1] + " " + str(self.selectionAnnee) + "[/b]"
    
    def on_bouton_navigation(self, args):
        if args.text == "<" : navigation = -1
        if args.text == ">" : navigation = +1
        self.selectionMois += navigation
        if self.selectionMois > 12 :
            self.selectionAnnee += 1
            self.selectionMois = 1
        if self.selectionMois == 0 :
            self.selectionMois = 12
            self.selectionAnnee -= 1
        
        self.box_grille.clear_widgets()
        self.RemplissageJours() 
        
    def on_release(self, event):
        date = datetime.date(self.selectionAnnee, self.selectionMois, int(event.text))
        if self.callback != None :
            self.callback(date)
        self.dismiss() 

    def on_dismiss(self, *arg):
        pass
Example #44
0
class Workspace(ScrollView):
    """
    Workspace is where user can view expression, configure them or simply choose to delete expressions.
    """
    def __init__(self, **kwargs):
        super(Workspace, self).__init__(**kwargs)
        self.line_number = 1
        self.expression_list = []
        self.y_pos = .8
        self.current_variable_names = []
        self.layout = GridLayout(cols=1, padding=10, spacing=10, size_hint=(None, None), width = 500)
        self.layout.bind(minimum_height=self.layout.setter('height'))
      
    """
    Draw the expression to the workspace layout
    """
    def draw(self):
        self.add_widget(self.layout)

    """
    Update the current list of variable names after a program is run
    """
    def update_variable_names(self, var):
        self.current_variable_names = var

    """
    "Clear the workspace when a new program is selected by the user
    """        
    def clear(self):
        self.expression_list = []
        self.y_pos = .8
        self.line_number = 1
        self.layout.clear_widgets()

    """
    Create relevant expression according to the expression buttons clicked in the command panel
    """

    def add_expression(self, instance):
        #exp = LetLayout(line, size_hint=(None, None),  pos_hint={'x':.2,'y':self.y_pos})
        if instance.text == 'LET':
            exp = LetLayout(self.line_number, self.current_variable_names, pos_hint={'x': .2, 'y': self.y_pos})
        elif instance.text == 'PRINT':
            exp = PrintLayout(self.line_number, pos_hint={'x': .2, 'y': self.y_pos})
        elif instance.text == 'GOTO':
            exp = GotoLayout(self.line_number, pos_hint={'x': .2, 'y': self.y_pos})
        elif instance.text == 'IF':
            exp = IfLayout(self.line_number, self.current_variable_names, pos_hint={'x': .2, 'y': self.y_pos})
        elif instance.text == 'GOSUB':
            exp = GoSubLayout(self.line_number, pos_hint={'x': .2, 'y': self.y_pos})
        elif instance.text == 'RETURN':
            exp = ReturnLayout(self.line_number,  pos_hint={'x': .2, 'y': self.y_pos})
        elif instance.text == 'END':
            exp = EndLayout(self.line_number, pos_hint={'x': .2, 'y': self.y_pos})

        self.line_number += 1
        # bind the delete event when user clicks on the delete button
        exp.btn_delete.fbind('on_press', self.delete_expression, expression=exp)
        
        exp.draw()
        self.layout.add_widget(exp)
        
        self.y_pos -= .1
        self.expression_list.append(exp)

    def on_touch_down(self, t):
        super(Workspace, self).on_touch_down(t)

        #t.apply_transform_2d(self.layout.to_local)
       # for widget in self.layout.walk():
            #print widget.on_touch_down(t)
           # print t
            #if widget.id == 'LET':
            #       print widget.on_touch_down(t)
    #            print "\n"
    #            print widget.collide_point(*t.pos)
    #            print widget
    #            print t
    #            print widget.x
    #            print widget.y

        #if self.collide_point(*t.pos):
        #    for widget in self.layout.walk():
        #        #if widget.collide_point(*t.pos):
        #        if widget.id == 'LET':
        #           print widget.on_touch_down(t)
                   #print widget.get_line_number()
                       #print("\n{} -> {}".format("Line number", widget.get_line_number()))
                   



    """
    Delete each expression from the workspace. This method is triggered when delete button is clicked
    """

    def delete_expression(self, instance, expression):
        self.layout.remove_widget(expression)
        self.expression_list.remove(expression)
        #self.line_number -= 1

    """
    Get all the expressions from the workspace
    """
    def get_expressions(self):
        return self.expression_list
Example #45
0
class MoonboardAppLayout(GridLayout):


    def __init__(self, **kwargs):
        super(MoonboardAppLayout, self).__init__(**kwargs)
        self.cols = 2
        self.rows = 2
        self.db = DbCon()
        global Routes, problemButton, filterBox, FilterLabel, filteredCommandStr, orderCommandStr, pageIndex, MoonLayout
        MoonLayout = "2017/"
        filteredCommandStr = ""
        orderCommandStr = "ORDER BY RAND() "
        pageIndex = 0
        Routes = self.db.get_rows()
        problemButton = [None] * len(Routes)
        filterBox = [None] * 21
        FilterLabel = [None] * 20
        filterBox[20] = False
        self.moonImages = [None] * 240
        self.problemList = GridLayout(cols=1, size_hint_y=None)
        self.problemList.bind(minimum_height=self.problemList.setter('height'))
        toggleText = ["6B+/V4+", "6C/V5", "6C+/V5+", "7A/V6", "7A+/V7", "7B/V8", "7B+/V8+", "7C/V9", "7C+/V10", "8A/V11", "8A+/V12", "8B/V13", "8B+/V14", "3 UserRating",
                      "2 UserRating", "1 Star", "0 UserRating", "Popular", "Newest", "Benchmarks"]
        for i in range(len(Routes)):
            problemButton[i] = Problem(
                text=(Routes[i][1] + '\n' + "Set By: " + Routes[i][10].encode('utf-8')) + '\n' + "Grade: " + Routes[i][2] + " UserRating: " + str(Routes[i][19]) + '\n' + '     ' + "Repeats: " + str(Routes[i][20]),
                size_hint_y=None)
            problemButton[i].route = Routes[i][34:68]
            problemButton[i].routeName = Routes[i][1]
            problemButton[i].setterName = str(Routes[i][10])
            #problemButton[i].gradeUK = str(Routes[i][2])
            problemButton[i].Grade = str(Routes[i][2])
            problemButton[i].UserRating = Routes[i][19]
            #problemButton[i].moves = Routes[i][5]
            problemButton[i].repeats = Routes[i][20]
            self.problemList.add_widget(problemButton[i])
        self.moonImageGroup = moonBoardProblemImage()
        self.temp = 0
        for i in range(19):
            for j in range(12):
                self.imageStr = str("images/" + MoonLayout + "moon-" + str(i) + "-" + str(j) + ".png")
                global LED_ROUTE_IMAGES
                LED_ROUTE_IMAGES[self.temp] = moonBoardImage(source=self.imageStr, size_hint_y=1, size_hint_x=1,
                                                             allow_stretch=True, keep_ratio=False)
                self.temp += 1
        for i in range(228):
            self.moonImageGroup.add_widget(LED_ROUTE_IMAGES[i])

        self.moonboardProblemsScroll = ScrollView()
        self.search_field = BoxLayout()
        self.navigation_field = BoxLayout()
        self.customizeBox = GridLayout(cols=1, size_hint_y=None)
        self.search_input = TextInput(text="", multiline=False)
        self.search_button = SearchButton(text="search", on_press=self.search)
        self.next_page_button = Button(text=">", on_press=self.pageIncrease)
        self.prev_page_button = Button(text="<", on_press=self.pageDecrease)
        self.customize = Button(text="Create Your Own!", on_press=self.custom_screen)
        self.return_home = Button(text="Return Home", on_press=self.home_screen)
        self.searchGrid = GridLayout(cols=1)
        self.navigateGrid = GridLayout(rows=2, orientation="vertical", size_hint_y=None)
        self.filterGroup = GridLayout(cols=4)
        self.add_widget(self.navigateGrid)
        self.add_widget(self.customizeBox)
        self.moonboardProblemsScroll.add_widget(self.problemList)
        self.add_widget(self.moonboardProblemsScroll)
        self.add_widget(self.searchGrid)

        for i in range(len(toggleText)):

            if toggleText[i] == "Popular":
                filterBox[i] = FilterBox(on_press=self.filter, active=False)
            elif toggleText[i] == "Newest":
                filterBox[i] = FilterBox(on_press=self.filter, active=True)
            elif toggleText[i] == "Benchmarks":
               filterBox[i] = FilterBox(on_press=self.filter, active=False)
            else:
                filterBox[i] = FilterBox(on_press=self.filter, active=True)
            FilterLabel[i] = Label()
            FilterLabel[i].text = toggleText[i]
            self.filterGroup.add_widget(filterBox[i])
            self.filterGroup.add_widget(FilterLabel[i])
        self.searchGrid.add_widget(self.filterGroup)
        self.searchGrid.add_widget(self.moonImageGroup)
        self.search_field.add_widget(self.search_input)
        self.search_field.add_widget(self.search_button)
        self.navigation_field.add_widget(self.prev_page_button)
        self.navigation_field.add_widget(self.next_page_button)
        self.navigateGrid.add_widget(self.search_field)
        self.navigateGrid.add_widget(self.navigation_field)
        self.customizeBox.add_widget(self.customize)



    def pageIncrease(self, pageNum):  #TODO account for something like remaining 99 if there isn't an even search
        global Routes, pageIndex, filterBox
        filterBox[20] = False
        if (len(Routes) > 9):
            pageIndex+=1
        else:
            pageIndex+=0
        self.filter()


    def pageDecrease(self, pageNum):  #TODO account for something like remaining 99 if there isn't an even search
        global Routes, pageIndex, filterBox
        filterBox[20] = False
        if (pageIndex > 0):
            pageIndex-=1
        else:
            pageIndex+=0
        self.filter()

    def creationScreen(self, *args):
        return 0

    def filter_table(self, search=""):
        global Routes, filterBox, pageIndex
        Routes = self.db.get_rows_filtered(True,filterBox[0].active, filterBox[1].active, filterBox[2].active,
                                           filterBox[3].active, filterBox[4].active, filterBox[5].active,
                                           filterBox[6].active, filterBox[7].active, filterBox[8].active,
                                           filterBox[9].active, filterBox[10].active, filterBox[11].active,
                                           filterBox[12].active, filterBox[13].active, filterBox[14].active,
                                           filterBox[15].active, filterBox[16].active, filterBox[17].active,
                                           filterBox[18].active, filterBox[19].active, search)
        print(len(Routes))
        for index in range(len(Routes)):
            problemButton[index] = Problem(
                text=(Routes[index][1] + '\n' + "Set By: " + Routes[index][10].encode('utf-8')) + '\n' + "Grade: " + Routes[index][
                    2] + " UserRating: " + str(Routes[index][19]) + '\n' + '     ' + "Repeats: " + str(Routes[index][20]),
                size_hint_y=None)
            problemButton[index].route = Routes[index][34:68]
            problemButton[index].routeName = Routes[index][1]
            problemButton[index].setterName = str(Routes[index][10])
            # problemButton[i].gradeUK = str(Routes[i][2])
            problemButton[index].Grade = str(Routes[index][2])
            problemButton[index].UserRating = Routes[index][19]
            # problemButton[i].moves = Routes[i][5]
            problemButton[index].repeats = Routes[index][20]
            self.problemList.add_widget(problemButton[index])


    def update_table(self, search=""):
        global Routes
        Routes = self.db.get_rows_searched(search)
        print(len(Routes))
        for index in range(len(Routes)):
            problemButton[index] = Problem(
                text=(Routes[index][1] + '\n' + "Set By: " + Routes[index][10].encode('utf-8')) + '\n' + "Grade: " +
                     Routes[index][
                         2] + " UserRating: " + str(Routes[index][19]) + '\n' + '     ' + "Repeats: " + str(
                    Routes[index][20]),
                size_hint_y=None)
            # problemButton[i].route = Routes[i][7:211]
            problemButton[index].route = Routes[index][34:68]
            problemButton[index].routeName = Routes[index][1]
            problemButton[index].setterName = str(Routes[index][10])
            # problemButton[i].gradeUK = str(Routes[i][2])
            problemButton[index].Grade = str(Routes[index][2])
            problemButton[index].UserRating = Routes[index][19]
            # problemButton[i].moves = Routes[i][5]
            problemButton[index].repeats = Routes[index][20]
            self.problemList.add_widget(problemButton[index])

    def clear_table(self):
        self.problemList.clear_widgets()

    def custom_screen(self, custom):
        self.clear_widgets()

        self.cols = 1
        self.return_home.size_hint_y = None
        self.moonImageGroup = moonBoardProblemImage()
        self.temp = 0
        for i in range(19):
            for j in range(12):
                self.imageStr = str("images/" + MoonLayout + "moon-" + str(i) + "-" + str(j) + ".png")
                global LED_ROUTE_IMAGES
                LED_ROUTE_IMAGES[self.temp] = moonBoardButton(background_normal=self.imageStr, background_down=self.imageStr, size_hint_y=1, size_hint_x=1,
                                                             allow_stretch=False, keep_ratio=True, border=(0,0,0,0))
                self.temp += 1
        for i in range(228):
            self.moonImageGroup.add_widget(LED_ROUTE_IMAGES[i])

        self.add_widget(self.moonImageGroup)
        self.add_widget(self.return_home)

    def home_screen(self, home):
        self.clear_widgets()
        self.__init__()


    def search(self, *args):
        global pageIndex
        pageIndex = 0
        self.clear_table()
        if "\'" in self.search_input.text:
            temp = self.search_input.text
            temp = temp.replace("'","+[^.apostrophe.]+")
            try:
                self.update_table(temp)
            except:
                pass
        elif "\\" in self.search_input.text:
                temp = self.search_input.text
                temp = temp.replace("\\", "+[^.solidus.]+")
                try:
                    self.update_table(temp)
                except:
                    pass
        elif self.search_input.text == '':
            temp = self.search_input.text
            temp = temp.replace("",".*.*")
            try:
                self.filter_table(temp)
            except:
                pass
        else:
            try:
                self.update_table(self.search_input.text)
            except:
                pass

    def filter(self, *args):
        self.clear_table()
        if "\'" in self.search_input.text:
            temp = self.search_input.text
            temp = temp.replace("'","+[^.apostrophe.]+")
            try:
                self.filter_table(temp)
            except:
                pass
        elif "\\" in self.search_input.text:
                temp = self.search_input.text
                temp = temp.replace("\\", "+[[.solidus.]]+")
                try:
                    self.filter_table(temp)
                except:
                    pass
        elif self.search_input.text == '':
            temp = self.search_input.text
            temp = temp.replace("",".*.*")
            try:
                self.filter_table(temp)
            except:
                pass
        else:
            try:
                self.filter_table(self.search_input.text)
            except:
                pass
Example #46
0
class Spotlight(App):
	''' This class represents the kivy app that will run the spotlight '''

	def __init__(self, **kwargs):
		super(Spotlight, self).__init__(**kwargs)
		# fixed width of the app, will never change
		self._width = kwargs.get('width', 500)
		# tells how many entries can be displayed on the screen at the same time. The rest will be accessible via a scroller
		self._max_results_displayed = kwargs.get('max_results_displayed', 5)
		# gives the height of the separators that will be used between each entry
		self._sep_height = kwargs.get('sep_height', 1)
		# static height of the main search bar: SearchInput
		self._search_field_height = kwargs.get('search_field_height', 35)
		# height of each entry
		self._result_height = kwargs.get('result_height', 25)
		# this is the spacing between the search bar and the scroller containing the entries
		self._spacing = kwargs.get('spacing', 1)
		# this is the padding of the main window
		self._padding = 5
		# this is the space between each separator/result in the dropdown list
		self._result_spacing = kwargs.get('result_spacing', 1)
		# color of a non-selected entry
		self._inactive_button_color = (.0,.0,.0, 0)
		# color of a selected entry
		self._active_button_color = (.4, .4, .4, 1)
		# store all the visible entries on the screen as a pair (button, separator) for convenience
		self._results = []
		# index of the result that is currently highlighted
		self._highlight_index = -1
		# these 3 variables are the 3 callbacks that the controller can input
		self._on_build = None
		self._on_enter = None
		self._on_text = None
		# this field holds a preset number of buttons for efficiency
		self._button_pool = []
		# parse the callbacks passed in the constructor
		self.user_bind(**kwargs)
		self.build_window()
		# update the window size
		self.update_window()

	def user_bind(self, **kwargs):
		''' this function saves the callbacks passed to this function into the 3 available holders '''
		# this event is triggered when the application is drawn for the first time
		self._on_build = kwargs.get('on_build', self._on_build)
		# this event is triggered when the user presses enter
		self._on_enter = kwargs.get('on_enter', self._on_enter)
		# this even is triggered whenever the text in the search field is changed
		self._on_text = kwargs.get('on_text', self._on_text)

	def on_start(self):
		'''  when the window is drawn and the application started we update the size of the window '''
		self.update_window()

	def build_window(self):
		''' this function builds the whole app '''
		self._search_field = SearchInput(multiline=False, focus=True, realdonly=False, height=self._search_field_height, size_hint=(1, None), markup=True,
			valign='middle', font_size = 20, font_name = 'data/fonts/DejaVuSans.ttf')
		self._search_field.bind(focus=self._on_focus)
		self._search_field._keyboard.bind(on_key_down=self._on_keyboard_down)
		self._search_field.background_active = ''
		self._search_field.font_size = 20
		self._search_field.bind(on_text_validate = self._on_text_validate)
		self._search_field.bind(text = self._on_new_text)
		self._search_field.text = ''
		self._drop_down_list = GridLayout(cols=1, width=self._width, spacing=self._result_spacing, size_hint = (None, None))
		self._drop_down_list.bind(minimum_height = self._drop_down_list.setter('height'))
		self._scroller = ScrollView(scroll_distance=10, scroll_type=['bars'], do_scroll_x=False, bar_width=10, size_hint=(1, 1))
		self._scroller.add_widget(self._drop_down_list)
		self._layout = ColoredGridLayout(cols=1, width=self._width, height=self._search_field_height, padding=(self._padding, self._padding), spacing=self._spacing*2)
		self._layout.add_widget(self._search_field)
		self._layout.add_widget(self._scroller)
		if self._on_build:
			self._on_build()
		return self._layout

	def build(self):
		return self._layout

	def _unbind_all(self):
		self._search_field.unbind(focus=self._on_focus)
		self._search_field._keyboard.unbind(on_key_down=self._on_keyboard_down)
		self._search_field.unbind(on_text_validate = self._on_text_validate)
		self._search_field.unbind(text = self._on_new_text)
		self._drop_down_list.unbind(minimum_height = self._drop_down_list.setter('height'))
		for btn in self._button_pool:
			btn.unbind(width = button_width_setter)
			btn.unbind(on_press=self._on_click)
			btn.unbind(texture_size=btn.setter('text_size'))

	def _on_new_text(self, value, text):
		if self._on_text:
			self._on_text(self, value, text)

	def _on_text_validate(self, value):
		''' when the user pressed enter, we forward the callback to the controller with the current hightlight index '''
		if self._on_enter:
			ret = self._on_enter(value, self._highlight_index)
			if ret:
				self._unbind_all()
				self.stop()

	def _on_focus(self, instance, value):
		''' this function is called whenever the focus of the search field changes. We do NOT allow defocus '''
		if not value:
			self._search_field.focus = True
			# since the search field has to re-claim the keyboard, we re-bind our callback
			self._search_field._keyboard.bind(on_key_down=self._on_keyboard_down)

	def update_window(self, *args):
		''' based on the current amount of entries shown, we adapt the size of the window '''
		result_count = len(self._results)
		win_width = 2*self._padding + self._width
		win_height = 2*self._padding + self._search_field_height + self._spacing + (self._result_spacing * 2 + self._result_height + self._sep_height) * result_count
		max_height = 2*self._padding + self._search_field_height + self._spacing + (self._result_spacing * 2 + self._result_height + self._sep_height) * self._max_results_displayed
		if self._app_window:
			self._app_window.size = win_width, min(win_height, max_height)

	def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
		''' we handle 3 keys: up (resp. down) to hightlight the entry above (resp. below) and escape to quit the application '''
		if keycode[1] == 'up':
			self._highlight_up()  
		elif keycode[1] == 'down':
			self._highlight_down()
		elif keycode[1] == 'escape':
			keyboard.release()
			self._unbind_all()
			self.stop()
		else:
			# mark the key press as not handled
			return False
		# mark the key press as handled
		return True

	def pre_allocate(self, number):
		self._button_pool = []
		for _ in range(0, number):
			btn = Button(text='str', height=self._result_height, size_hint=(1, None), valign='middle',
					halign='left', background_color=self._inactive_button_color, markup = True, padding_x = 0)
			btn.bind(width = button_width_setter)
			btn.bind(on_press=self._on_click)
			btn.bind(texture_size=btn.setter('text_size'))
			btn.background_normal = ''
			btn.background_down = btn.background_normal
			self._button_pool.append(btn)

	def _build_button(self):
		if self._button_pool:
			return self._button_pool.pop()
		btn = Button(text='str', height=self._result_height, size_hint=(1, None), valign='middle',
					halign='left', background_color=self._inactive_button_color, markup = True, padding_x = 0)
		btn.bind(width = button_width_setter)
		btn.bind(on_press=self._on_click)
		btn.bind(texture_size=btn.setter('text_size'))
		btn.background_normal = ''
		btn.background_down = btn.background_normal
		return btn

	def _release_button(self, btn):
		btn.background_color = self._inactive_button_color
		self._button_pool.append(btn)

	def add_result(self, str, redraw = True):
		''' add a new entry to the dropdown list; an index is returned '''
		btn = self._build_button()
		btn.text = str
		sep = Separator(height = self._sep_height)
		self._drop_down_list.add_widget(sep)
		self._drop_down_list.add_widget(btn)
		self._results.append((btn, sep))
		# we reset the highlight
		self._highlight_reset()
		if redraw:
			self.update_window()
		return len(self._results)-1

	def get_result(self, idx):
		''' get a button object from an index - returned from a previous call to add_result '''
		if not idx < len(self._results) or not idx >= 0:
			return
		e, _ = self._results[idx]
		return e

	def remove_result(self, idx, redraw = True):
		''' remove a result object from its index - returned from a previous call to add_result '''
		if not idx < len(self._results) or not idx >= 0:
			return
		e, sep = self._results[idx]
		if sep:
			self._drop_down_list.remove_widget(sep)
		self._drop_down_list.remove_widget(e)
		self._results.remove((e, sep))
		self._release_button(e)
		# we reset the highlight
		self._highlight_reset()
		# resize the window accordingly
		if redraw:
			self.update_window()

	def clear_results(self, redraw = True):
		''' clear all the results '''
		for e, sep in self._results:
			self._release_button(e)
		self._drop_down_list.clear_widgets()
		self._results = []
		# we reset the highlight
		self._highlight_reset()
		# resize the window accordingly
		if redraw:
			self.update_window()

	def _on_click(self, instance):
		''' this callback is called whenever a click on a result is done; the highlight is adapted '''
		for i in range(0, len(self._results)):
			e, _ = self._results[i]
			if e is instance:
				offset = i-self._highlight_index
				self._highlight_update(offset)
				self._on_text_validate(1)
				break

	def _scroll_update(self):
		''' this function adapts the scroller to ensure that the highlighted object is visible '''
		highlight_reverse_index = len(self._results) - 1 - self._highlight_index
		item_lb = highlight_reverse_index * (self._result_spacing*2 + self._sep_height + self._result_height)
		item_ub = item_lb + self._result_height + self._result_spacing*2 + self._sep_height
		view_size = (self._result_spacing * 2 + self._result_height + self._sep_height) * self._max_results_displayed
		total_size = (self._result_spacing * 2 + self._result_height + self._sep_height) * len(self._results)
		lb = self._scroller.scroll_y * (total_size - view_size)
		ub = lb + view_size
		if item_lb < lb:
			self._scroller.scroll_y -= self._scroller.convert_distance_to_scroll(0, lb - item_lb)[1]
		elif item_ub > ub:
			self._scroller.scroll_y += self._scroller.convert_distance_to_scroll(0, item_ub - ub)[1]

	def _highlight_update(self, offset):
		''' move the hightlight by `offset' amount '''
		if self._highlight_index > -1 and self._highlight_index < len(self._results):
			e, sep = self._results[self._highlight_index]
			e.background_color = self._inactive_button_color
		self._highlight_index += offset
		self._highlight_index = min(self._highlight_index, len(self._results)-1)
		if self._results:
			self._highlight_index = max(self._highlight_index, 0)
		else:
			self._highlight_index = max(self._highlight_index, 1)
		if self._highlight_index > -1 and self._highlight_index < len(self._results):
			e, sep = self._results[self._highlight_index]
			e.background_color = self._active_button_color
			self._scroll_update()

	def _highlight_reset(self):
		offset = -self._highlight_index
		self._highlight_update(offset)

	def _highlight_up(self):
		self._highlight_update(-1)

	def _highlight_down(self):
		self._highlight_update(+1)

	def on_stop(self):
		pygame.display.quit()
		pass
Example #47
0
class MainLayout(GridLayout):
    def __init__(self, **kwargs):
        super(MainLayout, self).__init__(**kwargs)  
        self.command_stack = []
        self.cols = 2
        self.orientation = "vertical"
        self.padding = 10
        self.y_pos= .8
       
        self.left_layout = GridLayout(cols=1,  pos=(5,-10))      

        self.spinner = Spinner( text = 'Menu', values =('New', 'Save', 'Clear Message Box','Exit'), size_hint =(None, None), size=(200,44), pos_hint={'x':.1, 'y':.9})
        self.left_layout.add_widget(self.spinner)

        self.let_button = Button(text="LET", size_hint =(None, None), size=(200,44),pos_hint={'x':.1, 'y':.7})
        self.left_layout.add_widget(self.let_button)
        
        self.print_button = Button(text="PRINT", size_hint =(None, None), size=(200,44),pos_hint={'x':.1, 'y':.6})
        self.left_layout.add_widget(self.print_button) 

        self.run_button = Button(text="RUN", size_hint =(None, None), size=(200,44),pos_hint={'x':.1, 'y':.6})
        self.left_layout.add_widget(self.run_button)
         
        self.add_widget(self.left_layout)

        self.orientation = "horizontal"

        self.grid_layout = GridLayout(cols=1,  padding=10, spacing=10, size_hint=(None, None), width=500)
        self.grid_layout.bind(minimum_height=self.grid_layout.setter('height'))
        self.right_layout = ScrollView(size_hint=(None, None),size=(500, 380), pos_hint={'center_x': .5, 'center_y': .5}, do_scroll_x=False, do_scroll_y=True)
        self.add_widget(self.right_layout)
        
       
        self.right_layout.add_widget(self.grid_layout)
        
        #self.right_layout = FloatLayout(pos=(200, -10) ,  size_hint=(.5,1))
        #self.right_layout = GridLayout(cols=1, pos=(300,-10))  
        #self.add_widget(self.right_layout)

        self.bottom_layout = GridLayout()
        self.comment = TextInput(text='Output is shown here..', width= 800, height=200)    
        
        self.bottom_layout.add_widget(self.comment)
        #self.bottom_layout.add_widget(TextInput())
        
        self.add_widget(self.bottom_layout)       
        
        self.let_button.bind(on_press =self.add_let)
        self.print_button.bind(on_press = self.add_print)
        self.spinner.bind(text = self.new_program_option)
        self.run_button.bind(on_press = self.run_app)
   

    def new_program_option(self, instance, option):
        if option == 'New':
             self.new_program()
             self.spinner.text = 'Menu'
             self.command_stack=[]
        elif option == 'Exit':
            sys.exit()
        elif option == 'Clear Message Box':
            self.spinner.text = 'Menu'
            self.comment.text=""

    def new_program(self):
        self.grid_layout.clear_widgets() # clear just the widgets inside the grid layout
        self.y_pos = .8

    def add_let(self, instance):
        line = len(self.command_stack) + 1
        command = LetLayout(line,size_hint=(None, None),  pos_hint={'x':.2,'y':self.y_pos})
        self.grid_layout.add_widget(command)
        self.y_pos -= .1
        self.command_stack.append(command)

    def add_print(self, instance):
        line = len(self.command_stack) + 1
        command = PrintLayout(line, size_hint=(None, None),  pos_hint={ 'x':.2,'y':self.y_pos})
        self.grid_layout.add_widget(command)
        self.y_pos -= .1
        self.command_stack.append(command)


    def run_app(self, instance):
        i = Interpreter()
        line_number = 1
        for cmd in self.command_stack:
            line = cmd.get_command()
            i.add_line(line_number, line)
            line_number = line_number + 1

        i.run()
        output = i.get_output()
        variables = i.get_variables()

        self.comment.text = ""
        self.comment.insert_text('\n Output : \n')
        for value in output:
            self.comment.insert_text(' ' + str(value)+ '\n')

        self.comment.insert_text('\n Memory: \n')
        self.comment.insert_text(' Variable \t Value \n')
        for var in variables.keys():
            value = ' \t' + var + ' \t\t\t ' + str(variables[var]) + '\n'
            self.comment.insert_text(' ' + str(value))



    def get_command_stack(self):
        return self.command_stack
class SNS(Screen):
    statusList = ListProperty()
    snsdata = ListProperty()
    channeldata = ListProperty()
    all_status = []
    
    
    def __init__(self, **kwargs):
        super(SNS, self).__init__(**kwargs)
        self.ch = list(sp.keys())
        self.current_channel_intext = 'All Platform'
        self.current_channel=None
        self.ids._channel_spinner.bind(text=self.change_channel)
        self.ch.sort()
        self.ch.insert(0, 'All Platform')
        
        self.STATUS_SIZE = 20
        self.SHOW_ON_SCREEN_FREQUENCE = 0.5
        
        self.moreClickTimes = 0
        self.first_status = None
        self.ids._channel_spinner.values = self.ch
        self.dropdownmenu = DropDownMenu()
        
        self.statusGridLayout = GridLayout(cols=1, padding=5,size_hint=(1, None))
        self.statusGridLayout.bind(minimum_height=self.statusGridLayout.setter('height'))
        
        self.StatusListview = self.ids._scroll_view_status
        
        self.StatusListview.add_widget(self.statusGridLayout)
        
        if exists('conf/status.json'):
            with open('conf/status.json','rb') as fd:
                statusdata = json.load(fd)
            self.statusList = statusdata
            
        #binding test
        #self.StatusListview.bind(scroll_y=self.my_y_callback)
        Logger.debug ('The device window size is ' + str(Window.size))
        #for status in self.statusList:
         #   print status['status_content']

    def change_channel(self, spinner, text):
        channel = spinner.text
        if not channel or channel == self.current_channel: return
        self.current_channel = channel != 'All Platform' and channel or None
        self.current_channel_intext = channel != 'All Platform' and channel or 'All Platform'
        Logger.debug('self.current_channel_intext is ' + str(self.current_channel_intext))
        Logger.debug('self.current_channel is ' + str(self.current_channel))
        return True
        
    def insert_status(self,status,status_index = None):
        if status in self.all_status:
            return False

        if status_index is None:status_index = len(self.all_status)

        self.all_status.insert(status_index,status)
        self.__insert_status(status,status_index)
        return True

    def __insert_status(self,status,index):        
        data = status.parsed
        try: text = data.title
        except: text = data.text
        title_text = '%s said at %s,' % (data.username, data.time)
        #title_text = '%s at %s' % (data.username, utc2str(data.time))
        content_text = text
        
        try:origin_name = status.parsed.username_origin
        except:origin_name = None
        
        #---------------Finding attachment and handling----------------------#

        try: attachs = data.attachments
        except: attachs = None
        
        self.getKeywords(content_text,data.username,data.time,status.ID,origin_name,attachs,False)
        content_text = DividingUnicode.div(content_text,30)
        
        #-------------------status inserted to the snsdata------------------------#
                               
        self.snsdata.append({'title':title_text, 
                             'content':content_text, 
                             'name':data.username,
                             'time':data.time,
                             'ID':status.ID,
                             'origin_name':origin_name,
                             'attachments':attachs})
        #scroll view operation
        newItem = SNSListItem(sns_content=content_text,sns_title=title_text,sns_index=index)
        
        #---------------------Add the attachment to the itemview----------------------# 
        itemlayout = newItem.ids.attachment_layout_item
         
        for att in attachs:
            if att['type'] == 'picture':
                try: index = att['format'].index('link')
                except: index = None
                if index != None:
                    if att['data'].find('.gif') == -1:
                        att_image = AsyncImage(source=att['data'],size_hint_y=.2)
                        itemlayout.add_widget(att_image)
                        # break if only one image need add to the home time view
                        break
            elif att['type'] == 'link':
                Logger.info(att['data'])
                
        #---------------------------------------------------------------------#
        self.statusGridLayout.add_widget(newItem)

    def getKeywords(self,status_content,status_username=None,status_time=None,
                    statusID=None,username_origin=None,attachments=None,is_touch_in=False):
        '''
        to store full information, we did extract the keywords, 
        now we just save the full status to keep all useful information
        '''
        #tag version
        '''
        tags = extractKeywords(status)
        
        tagsInList = False
        index = 0
        for status in self.statusList:
            if tags == status['keywords']:
                index = self.statusList.index(status)
                status['frequency'] += 1
                tagsInList = True
        
        if not tagsInList:
            self.statusList.append({'keywords':tags,
                                    'frequency' : 1,
                                    'time' : 0,
                                    'like' :None,
                                    'currentTime' :time.strftime("%b %d %H:%M:%S")
                                    })
            index = len(self.statusList)-1
        '''
        #----------------------------------------------------#
        #full status version
        
        statusInList = False
        index = 0
        for status in self.statusList:
            if statusID == status['status_ID']:
                index = self.statusList.index(status)
                if is_touch_in:
                    status['frequency'] += 1
                statusInList = True
        
        if not statusInList:
            self.statusList.append({'status_ID':statusID,
                                    'status_content':status_content,
                                    'status_username':status_username,
                                    'user_name_origin':username_origin,
                                    'status_time':status_time,
                                    'frequency' : 0,
                                    'time' : 0,
                                    'like' :None,
                                    'currentTime' :time.strftime("%a, %d %b %Y %H:%M:%S"),
                                    'show_on_screen_time':0,
                                    'speed_of_on_Screen':0,
                                    'attachments_contain':attachments
                                    })
            index = len(self.statusList)-1
        #------------------------------------------------------#

        '''                        
        with open('conf/status.json', 'wb') as fd:
            json.dump(self.statusList, fd,indent = 2)
        '''
                
        return index

    def sns_args_converter(self, row_index, item):
        return {
            'sns_index': row_index,
            'sns_content': item['content'],
            'sns_title': item['title']}

    def refresh_status(self):
        Clock.unschedule(self.status_shown_on_screen)
        self.moreClickTimes = 0
        temp_length = len(self.snsdata)
        del self.all_status[0:len(self.all_status)]
        del self.snsdata[0:len(self.snsdata)]
        self.statusGridLayout.clear_widgets()
        
        if not self.current_channel == None:
            if temp_length>0:
                hl = sp.home_timeline(self.STATUS_SIZE+temp_length, self.current_channel)
            else:
                hl = sp.home_timeline(self.STATUS_SIZE, self.current_channel)
        else:
            hl = sp.home_timeline(self.STATUS_SIZE, self.current_channel)

        i = 0
        
        if len(hl)>0:
            self.first_status = hl[0]
            Logger.debug('first status inserted')
        for s in hl:
            if self.insert_status(s, i):
                i += 1
                
        Logger.debug("length of sns data " +str (len(self.snsdata)))        
        self.StatusListview.scroll_y = 1
        
        #schedule the clock
        Clock.schedule_interval(self.status_shown_on_screen, self.SHOW_ON_SCREEN_FREQUENCE)
        return True
        
    def more_status(self):
        Logger.debug('The length of the sp is ' + str(len(sp)))
        self.moreClickTimes = self.moreClickTimes + 1
        n  = len(self.all_status) + len(sp) * 10 * self.moreClickTimes
        Logger.debug('The number n is ' + str(n))
        more_home_timeline = sp.home_timeline(n,self.current_channel)
        first_in_more = len(more_home_timeline)
        
        if self.first_status == None:
            self.refresh_status()
            self.moreClickTimes = self.moreClickTimes - 1
            return False

        
        '''
        i = 0
        for sta in more_home_timeline:
            if sta == first_status:
                first_in_more = i
                print 'first status in more status ' + str(i)
                break
            i+=1
        '''
        
        #Find the original fisrt status    
        for i in range(len(more_home_timeline)):
            if more_home_timeline[i].parsed.text==self.first_status.parsed.text:
                first_in_more = i
                Logger.debug('first status in more status ' + str(i))
                break
        
        
        i=0
        j=len(self.snsdata)
        for sta in more_home_timeline:
            if i >= first_in_more+self.STATUS_SIZE:
                if self.insert_status(sta, j):
                    j+=1
                    #print i, j
            i += 1
        Logger.debug("length of sns data "+ str(len(self.snsdata)))
            
        self.StatusListview.scroll_y = 1
        return True
    
    def my_y_callback(self,obj, value):
        Logger.debug('on listview', obj, 'scroll y changed to', value)
        Logger.debug('The status on the screen is ', self.status_shown_on_screen(obj, value))
    
    def scroll_speed(self):
        pass
    
    def status_shown_on_screen(self,obj=None, scroll_y=None):
        if scroll_y == None:
            scroll_y = self.StatusListview.scroll_y
        
        head_status = round((1-scroll_y)*(len(self.snsdata)-2.8))
        status_list_height = Window.size[1] - 90
        status_per_screen = round(status_list_height / 150)
        tail_status = head_status + status_per_screen - 1
        
        #record the shown on screen time
        #for i in range(int(head_status),int(tail_status+1)):
            #self.statusList[i]['show_on_screen_time'] += self.SHOW_ON_SCREEN_FREQUENCE
        #Logger.debug('The shown status is ' + str(head_status) + ' to ' + str(tail_status))
        
        return (head_status,tail_status)
    
    def save_status_feedback(self,obj=None, value=None):
        with open('conf/status.json', 'wb') as fd:
            json.dump(self.statusList, fd,indent = 2)
Example #49
0
class MainScreen(Screen):
    IMAGE_TYPE_LEFT = "left"
    IMAGE_TYPE_RIGHT = "right"
    current_images = None
    image1 = None
    image2 = None
    layout = None

    def choose(self, button):
        from HoneyApp import HoneyApp

        def get_date_diff_string():
            timestamp_diff = (datetime.datetime.fromtimestamp(self.current_images[self.IMAGE_TYPE_LEFT]['timestamp']) -
                              datetime.datetime.fromtimestamp(self.current_images[self.IMAGE_TYPE_RIGHT]['timestamp']))
            return str(abs(timestamp_diff.days)) + ' дней'

        if button.type == self.IMAGE_TYPE_LEFT:
            image_chosen_timestamp = self.current_images[self.IMAGE_TYPE_LEFT]['timestamp']
            image_another_timestamp = self.current_images[self.IMAGE_TYPE_RIGHT]['timestamp']
        else:
            image_chosen_timestamp = self.current_images[self.IMAGE_TYPE_RIGHT]['timestamp']
            image_another_timestamp = self.current_images[self.IMAGE_TYPE_LEFT]['timestamp']

        if image_chosen_timestamp < image_another_timestamp:
            status = True
        else:
            status = False

        modal = ModalView(size_hint=(None, None), size=(400, 200))
        if status:
            modal.bind(on_dismiss=self.renew_images)
            modal_data = random.choice(HoneyApp.success)
        else:
            modal_data = random.choice(HoneyApp.error)

        layout = GridLayout(cols=1, rows=2, on_touch_down=modal.dismiss)
        text = '[size=18][b]{text}[/b][/size]\n' \
               '[size=11]Эта фотография была сделана: [b]{image_date_chosen}[/b]\n' \
               'Дата второй фотографии: [b]{image_date_another}[/b]\n' \
               'Разница - [b]{date_diff}[/b][/size]'.\
            format(text=modal_data['text'],
                   image_date_chosen=datetime.datetime.fromtimestamp(image_chosen_timestamp).strftime('%d.%m.%Y %H:%M'),
                   image_date_another=datetime.datetime.fromtimestamp(image_another_timestamp).strftime('%d.%m.%Y %H:%M'),
                   date_diff=get_date_diff_string())

        layout.add_widget(Label(text=text, markup=True))
        layout.add_widget(Image(source=modal_data['filename']))
        modal.add_widget(layout)
        modal.open()

    def on_enter(self):
        from HoneyApp import HoneyApp
        self.layout = GridLayout(cols=2, rows=1, spacing=10, padding=10)

        parent_layout = FloatLayout(size=(0, 0))
        sound_btn = SoundButton(source=HoneyApp.SOUND_SETTINGS['image'], pos=(5, 5), size_hint=(0.1, 0.1))
        parent_layout.add_widget(sound_btn, 0)
        parent_layout.add_widget(self.layout, 1)

        self.add_widget(parent_layout)
        self.renew_images()

    def renew_images(self, modal=None):
        self.layout.clear_widgets()
        self.current_images = self.get_random_images()

        if self.image1:
            self.remove_widget(self.image1)
        if self.image2:
            self.remove_widget(self.image2)

        self.image1 = ImageButton(
            source=self.current_images[self.IMAGE_TYPE_LEFT]['filename'],
            type=self.IMAGE_TYPE_LEFT
        )
        self.image2 = ImageButton(
            source=self.current_images[self.IMAGE_TYPE_RIGHT]['filename'],
            type=self.IMAGE_TYPE_RIGHT,
        )
        self.image1.bind(on_press=self.choose)
        self.image2.bind(on_press=self.choose)

        self.layout.add_widget(self.image1)
        self.layout.add_widget(self.image2)

    def get_random_images(self):
        from HoneyApp import HoneyApp

        while True:
            image_random1 = random.choice(HoneyApp.images)
            image_random2 = random.choice(HoneyApp.images)

            if image_random1['filename'] == image_random2['filename']:
                continue
            else:
                return {self.IMAGE_TYPE_LEFT: image_random1, self.IMAGE_TYPE_RIGHT: image_random2}
Example #50
0
class LSystemsEdit(Screen):

    def __init__(self,**kwargs):
        super(LSystemsEdit, self).__init__(**kwargs)
        self.name="edit"
        self.main_layout=BoxLayout(orientation='horizontal')

        self.edit_layout=BoxLayout(orientation='vertical',size_hint_x=.4)
        #Text boxes
        self.name_input = TextInput(multiline=False,size_hint_y=None,height=sp(30))
        self.name_input.bind(text=self.on_text)
        self.angle = TextInput(multiline=False,size_hint_y=None,height=sp(30))
        self.angle.bind(text=self.on_text)
        self.axiom = TextInput(multiline=False,size_hint_y=None,height=sp(30))
        self.axiom.bind(text=self.on_text)
        self.rules = TextInput(multiline=True,size_hint=(1,.4))
        self.rules.bind(text=self.on_text)
        self.rule_chooser = GridLayout(cols=6,size_hint=(1,.2))
        #buttons for changing number of iterations
        self.iterations_buttons = BoxLayout(orientation = 'horizontal',size_hint_y=None,height=sp(30))
        self.minus = Button(text="-")
        self.iter_label = Label(text = "1")
        self.plus = Button(text = "+")
        self.minus.bind(on_press = self.iter_press)
        self.plus.bind(on_press = self.iter_press)
        self.iterations_buttons.add_widget(self.minus)
        self.iterations_buttons.add_widget(self.iter_label)
        self.iterations_buttons.add_widget(self.plus)        

        self.image = LSystemImage()

        self.edit_layout.add_widget(Label(text="[b]Name[/b]",markup=True,size_hint_y=None,height=sp(30)))
        self.edit_layout.add_widget(self.name_input)
        self.edit_layout.add_widget(Label(text="[b]Angle[/b]",markup=True,size_hint_y=None,height=sp(30)))
        self.edit_layout.add_widget(self.angle)
        self.edit_layout.add_widget(Label(text="[b]Axiom[/b]",markup=True,size_hint_y=None,height=sp(30)))
        self.edit_layout.add_widget(self.axiom)
        self.edit_layout.add_widget(Label(text="[b]Rules[/b]",markup=True,size_hint_y=None,height=sp(30)))
        self.edit_layout.add_widget(self.rules)
        self.edit_layout.add_widget((Label(text="[b]Choose rule to visualise[/b]",markup=True,size_hint_y=None,height=sp(30))))
        self.edit_layout.add_widget(self.rule_chooser)
        self.edit_layout.add_widget((Label(text="[b]Change number of iterations[/b]",markup=True,size_hint_y=None,height=sp(30))))
        self.edit_layout.add_widget(self.iterations_buttons)
        self.edit_layout.add_widget((Label(text="[b]L-systems syntax[/b]",markup=True,size_hint_y=None,height=sp(30))))
        syntax_label=ScrollableLabel()
        syntax_label.text = syntax
#        def f(*args,**kwargs): syntax_label.text_size = syntax_label.size
#        syntax_label.bind(size = f)


        self.edit_layout.add_widget(syntax_label)
        self.main_layout.add_widget(self.edit_layout)
        self.main_layout.add_widget(self.image)

        #self.load_lsystem(('quartet', ('fb', {'a': 'fbfa+hfa+fb-fa', 'h': '-', 'b': 'fb+fa-fb-jfbfa', 'j': '+', 'f': ''}, 90.0)))

        self.add_widget(self.main_layout)



    def iter_press(self,instance,*args):
        if instance.text == "+":
            iteration = int(self.iter_label.text)+1
        else:
            iteration = int(self.iter_label.text)-1
            if iteration<0: iteration = 0
        self.image.set_iterations(iteration)
        self.iter_label.text = str(iteration)


    def set_rule_chooser(self):
        if self.lsystem:
            name,(axiom,rules,angle) = self.lsystem
        else:
            rules = {}
        self.rule_chooser.clear_widgets()
        for name in ["axiom"]+sorted(rules.keys()):
            btn = ToggleButton(text=name, group='rules',size_hint_y=None,height=sp(30))
            if name == 'axiom': btn.state = 'down'
            btn.bind(on_press = self.on_rule_choose)
            self.rule_chooser.add_widget(btn)


    def on_rule_choose(self,instance,*args):
        if self.lsystem:
            name,(axiom,rules,angle) = self.lsystem
            new_axiom = instance.text if instance.text!="axiom" else axiom
            self.image.set_lsystem((new_axiom,rules,angle))

    def on_text(self,instance,*args):
        self.get_lsystem()
        if self.lsystem:
            self.image.set_lsystem(self.lsystem[1])
            #self.image.set_iterations(1)
        self.set_rule_chooser()

    def load_lsystem(self,lsystem):
        name,(axiom,rules,angle) = lsystem
        self.name_input.text = name
        self.axiom.text = axiom
        self.angle.text = str(angle)
        self.rules.text = '\n'.join(["%s=%s"%(k,v) for (k,v) in sorted(rules.items())])

    def get_lsystem(self):
        name = self.name_input.text
        axiom = self.axiom.text.replace(" ","")
        angle=''
        try: angle = float(self.angle.text)
        except: angle = 0
        try: rules = dict([x.split("=") for x in self.rules.text.replace(" ","").split("\n") if x])
        except: rules = {}
        self.lsystem = name,(axiom,rules,angle)
Example #51
0
class MainScreen(Screen):
  def __init__(self, **kwargs):
    super(MainScreen, self).__init__(**kwargs)

    mainLayout = GridLayout(cols=1)

    global window_height
    window_height = mainLayout.height
    # top
    btnBack = Button(text='Back', size_hint_x=0.1)
    
    self.lblPath = Label(size_hint_x=0.8, color = color['lblPath'])
    self.lblPath.anchors_x = 'left'
    btnAdd = Button(text='+', size_hint_x=0.1)
    topLayout = BoxLayout(size_hint_y = 0.1)
    topLayout.add_widget(btnBack)
    topLayout.add_widget(self.lblPath)
    topLayout.add_widget(btnAdd)
    mainLayout.add_widget(topLayout) 
    btnAdd.bind(on_press=self.addMenu)
    # Content
    scroll = ScrollView(size_hint=(1,1), do_scroll_x=False)
    self.contentLayout = GridLayout(cols = 1, padding = 10, spacing = 10, size_hint_y = None)
    self.contentLayout.bind(minimum_height=self.contentLayout.setter('height'))  # for scrolling
    scroll.add_widget(self.contentLayout)
    mainLayout.add_widget(scroll)
    btnBack.bind(on_press=self.goBack)

    self.add_widget(mainLayout)
    self.showTree()

    self.win = Window

    mainLayout.bind(
          size=self._update_rect,
          pos=self._update_rect)
    with mainLayout.canvas.before:
      Color(0.5, 0.8, 1, 0.9) 
      self.rect = Rectangle(
                  size=mainLayout.size,
                  pos=mainLayout.pos)
  def _update_rect(self, instance, value):
    self.rect.pos = instance.pos
    self.rect.size = instance.size

  def on_pre_enter(self, *args):
    self.win.bind(on_keyboard=self.keyboardHandler)
    self.showTree()
    
  def on_pre_leave(self):
    self.win.unbind(on_keyboard=self.keyboardHandler)

  def keyboardHandler(self, window, keycode1, keycode2, text, modifiers):
    if keycode1 == systemBtnBack:
      if tree.reachRoot():
        self.doExit()
      else:  
        self.goBack()
      return True
    return False

  def doExit(self, *args):
    self.contextMenu = ModalView(size_hint=(0.5, 0.5))
    mainLayout = BoxLayout(
        padding = 10,
        spacing = 10,
        pos_hint = {'center_x': 0.5, 'center_y': 0.5}, 
        size_hint = (0.7, 0.8), 
        orientation = 'vertical')
    mainLayout.add_widget(Label(text='Exit?'))
    chooserField = BoxLayout()
    btnAddBranch = Button(text='yes')
    chooserField.add_widget(btnAddBranch)
    btnAddBranch.bind(on_press=MainScreen.exit)
    close = Button(text='no')
    close.bind(on_release=self.contextMenu.dismiss)
    chooserField.add_widget(close)
    mainLayout.add_widget(chooserField)

    self.contextMenu.add_widget(mainLayout)
    self.contextMenu.open()
  
  def exit(*args):
    raise wantExit

  def showTree(self, *args):  
    self.contentLayout.clear_widgets()
    self.lblPath.text = tree.getPath()
    counter = 0
    for cur in tree.curItem().get():
      if isinstance(cur, Branch):
        btnBranch = ButtonBranch(text=cur.name, num=counter, outward=self)
        btnBranch.bind(on_release=btnBranch.goHere)
        btnBranch.bind(on_release=self.showTree)
        self.contentLayout.add_widget(btnBranch)
      if isinstance(cur, Leaf):
        self.contentLayout.add_widget(ButtonLeaf(text=cur.name, num=counter, outward=self))
      counter += 1  

  def goBack(self, *args):
    if not tree.reachRoot():
      tree.down()
      self.showTree()

  def addMenu(self, *args):
    self.contextMenu = ModalView(size_hint=(0.5, 0.5))
    mainLayout = BoxLayout(
        padding = 10,
        spacing = 10,
        pos_hint = {'center_x': 0.5, 'center_y': 0.5}, 
        size_hint = (0.7, 0.8), 
        orientation = 'vertical')
    mainLayout.add_widget(Label(text='Add:'))
    inputField = BoxLayout()
    inputField.add_widget(Label(text='name: ', size_hint_x=0.3))
    self.textField = TextInput(multiline=False, focus=True)
    inputField.add_widget(self.textField)
    mainLayout.add_widget(inputField)
    btnAddBranch = Button(text='Add Branch')
    btnAddLeaf = Button(text='Add Leaf')
    mainLayout.add_widget(btnAddBranch)
    mainLayout.add_widget(btnAddLeaf)
    btnAddBranch.bind(on_press=self.addBranch)
    btnAddLeaf.bind(on_press=self.addLeaf)
    close = Button(text='close')
    close.bind(on_release=self.contextMenu.dismiss)
    mainLayout.add_widget(close)

    self.contextMenu.add_widget(mainLayout)
    self.contextMenu.open()
    
  def addBranch(self, *args):
    if self.textField.text != '':
      tree.curItem().add(Branch(name=self.textField.text))
      self.textField.text = ''
      self.contextMenu.dismiss()
      self.showTree()

  def addLeaf(self, *args):
    if self.textField.text != '':
      tree.curItem().add(Leaf(name=self.textField.text))
      self.textField.text = ''
      self.contextMenu.dismiss()
      self.showTree()
Example #52
0
class DatePicker(BoxLayout,Form):
    date=ObjectProperty(date.today())
    __stereotype__ = StringProperty('widget')
    
    def on_date(self,sender,value):
        self.data['date']=self.transform_date_oerp(value)
        self.data['date_display']=self.transform_date_human(value)
        self.populate_header()
        self.populate_body()
    
    def __init__(self, *args, **kwargs):
        super(DatePicker, self).__init__(**kwargs)
        self.orientation = "vertical"
        self.month_names = (_('Enero'),
                            _('Febrero'), 
                            _('Marzo'), 
                            _('Abril'), 
                            _('Mayo'), 
                            _('Junio'), 
                            _('Julio'), 
                            _('Agosto'), 
                            _('Septiembre'), 
                            _('Octubre'),
                            _('Noviembre'),
                            _('Diciembre'))
        if kwargs.has_key("month_names"):
            self.month_names = kwargs['month_names']
        self.header = BoxLayout(orientation = 'horizontal', 
                                size_hint = (1, 0.2))
        self.body = GridLayout(cols = 7)
        self.add_widget(self.header)
        self.add_widget(self.body)

        self.populate_body()
        self.populate_header()
        if kwargs.has_key("init_vals"):
            if kwargs["init_vals"].has_key('date') and kwargs["init_vals"]['date']!='':
                self.date=datetime.strptime(kwargs["init_vals"]['date'],'%Y-%m-%d')
        self.data['date']=self.transform_date_oerp(self.date)
        self.data['date_display']=self.transform_date_human(self.date)

    def populate_header(self, *args, **kwargs):
        self.header.clear_widgets()
        previous_month = Button(text = "<")
        previous_month.bind(on_press=partial(self.move_previous_month))
        next_month = Button(text = ">")
        next_month.bind(on_press=partial(self.move_next_month))
        month_year_text = self.month_names[self.date.month -1] + ' ' + str(self.date.year)
        current_month = Label(text=month_year_text, size_hint = (2, 1))

        self.header.add_widget(previous_month)
        self.header.add_widget(current_month)
        self.header.add_widget(next_month)

    def populate_body(self, *args, **kwargs):
        self.body.clear_widgets()
        date_cursor = date(self.date.year, self.date.month, 1)
        for filler in range(date_cursor.isoweekday()-1):
            self.body.add_widget(Label(text=""))
        while date_cursor.month == self.date.month:
            date_label = Button(text = str(date_cursor.day))
            date_label.bind(on_press=partial(self.set_date,day=date_cursor.day))
            if self.date.day == date_cursor.day:
                date_label.background_normal, date_label.background_down = date_label.background_down, date_label.background_normal
            self.body.add_widget(date_label)
            date_cursor += timedelta(days = 1)

    def set_date(self, *args, **kwargs):
        self.date = date(self.date.year, self.date.month, kwargs['day'])
        self.populate_body()
        self.populate_header()

    def move_next_month(self, *args, **kwargs):
        if self.date.month == 12:
            self.date = date(self.date.year + 1, 1,min(self.date.day,calendar.monthrange(self.date.year,1)[1]) )
        else:
            self.date = date(self.date.year, self.date.month + 1,min(self.date.day,calendar.monthrange(self.date.year, self.date.month +1)[1]))
        self.populate_header()
        self.populate_body()

    def move_previous_month(self, *args, **kwargs):
        if self.date.month == 1:
            self.date = date(self.date.year - 1, 12, min(self.date.day,calendar.monthrange(self.date.year,12)[1]))
        else:
            self.date = date(self.date.year, self.date.month -1, min(self.date.day,calendar.monthrange(self.date.year, self.date.month -1)[1]))
        self.populate_header()
        self.populate_body()

    def transform_date_oerp(self, date):
        select_date = str(date.year)+'-'+str(date.month).zfill(2)+'-'+str(date.day).zfill(2)
        return select_date

    def transform_date_human(self, date):
        select_date = str(date.day).zfill(2)+'-'+str(date.month).zfill(2)+'-'+str(date.year)
        return select_date
Example #53
0
class Dashboard(BoxLayout):
    """Home tab that displays user statistics"""
    def __init__(self,sm,**kwargs):
        super(Dashboard, self).__init__(**kwargs)
        self.sm = sm

        self.ahse_cred = 0      
        self.engr_cred = 0
        self.mth_cred = 0
        self.sci_cred = 0        
        will_grad = 'No'

        ## USER INFORMATION HALF ##
        self.info = GridLayout(rows=5,size_hint=(0.5,1.0))

        # User's Name #
        self.display_name = Label(size_hint=(1.0,0.05))

        # Grad Year #
        self.years = BoxLayout(size_hint=(1.0,0.1))

        year1 = BoxLayout(size_hint=(0.2,1.0))
        self.year1_check=CheckBox(active=False,group='year',size_hint=(0.1,1.0))
        self.year1_label = Label(text=str(2014),size_hint=(0.9,1.0))
        year1.add_widget(self.year1_label)
        year1.add_widget(self.year1_check)
        year2 = BoxLayout(size_hint=(0.2,1.0))
        self.year2_check=CheckBox(active=False,group='year',size_hint=(0.1,1.0))
        self.year2_label = Label(text=str(2015),size_hint=(0.9,1.0))
        year2.add_widget(self.year2_label)
        year2.add_widget(self.year2_check)
        year3 = BoxLayout(size_hint=(0.2,1.0))
        self.year3_check=CheckBox(active=False,group='year',size_hint=(0.1,1.0))
        self.year3_label = Label(text=str(2016),size_hint=(0.9,1.0))
        year3.add_widget(self.year3_label)
        year3.add_widget(self.year3_check)
        year4 = BoxLayout(size_hint=(0.2,1.0))
        self.year4_check=CheckBox(active=False,group='year',size_hint=(0.1,1.0))
        self.year4_label = Label(text=str(2017),size_hint=(0.9,1.0))
        year4.add_widget(self.year4_label)
        year4.add_widget(self.year4_check)

        self.years.add_widget(Label(size_hint=(0.1,1.0)))
        radio_buttons1=[year1,year2,year3,year4]        
        for button in radio_buttons1:
            self.years.add_widget(button)
        self.years.add_widget(Label(size_hint=(0.1,1.0)))
         
        # Major #  
        self.majors = GridLayout(cols=1,size_hint=(1.0,0.7))        
        ece = BoxLayout()
        self.ece_check = CheckBox(active=False,group='majors')
        self.ece_label = Label(text='ECE')
        ece.add_widget(Label())
        ece.add_widget(self.ece_label)
        ece.add_widget(self.ece_check)
        ece.add_widget(Label())
        meche = BoxLayout()       
        self.meche_check = CheckBox(active=False,group='majors')
        self.meche_label = Label(text='MechE')
        meche.add_widget(Label())
        meche.add_widget(self.meche_label)
        meche.add_widget(self.meche_check)
        meche.add_widget(Label())
        roboe = BoxLayout()       
        self.roboe_check = CheckBox(active=False,group='majors')
        self.roboe_label = Label(text='E:Robo')
        roboe.add_widget(Label())
        roboe.add_widget(self.roboe_label)
        roboe.add_widget(self.roboe_check)
        roboe.add_widget(Label())
        bioe = BoxLayout()       
        self.bioe_check = CheckBox(active=False,group='majors')
        self.bioe_label = Label(text='E:Bio')
        bioe.add_widget(Label())
        bioe.add_widget(self.bioe_label)
        bioe.add_widget(self.bioe_check)
        bioe.add_widget(Label())
        designe = BoxLayout()       
        self.designe_check = CheckBox(active=False,group='majors')
        self.designe_label = Label(text='E:Design')
        designe.add_widget(Label())
        designe.add_widget(self.designe_label)
        designe.add_widget(self.designe_check)
        designe.add_widget(Label())
        ec = BoxLayout()       
        self.ec_check = CheckBox(active=False,group='majors')
        self.ec_label = Label(text='E:C')
        ec.add_widget(Label())
        ec.add_widget(self.ec_label)
        ec.add_widget(self.ec_check)
        ec.add_widget(Label())
        syse= BoxLayout()       
        self.syse_check = CheckBox(active=False,group='majors')
        self.syse_label = Label(text='E:Sys')
        syse.add_widget(Label())
        syse.add_widget(self.syse_label)
        syse.add_widget(self.syse_check)
        syse.add_widget(Label())
        matscie = BoxLayout()       
        self.matscie_check = CheckBox(active=False,group='majors')
        self.matscie_label = Label(text='E:MatSci')
        matscie.add_widget(Label())
        matscie.add_widget(self.matscie_label)
        matscie.add_widget(self.matscie_check)
        matscie.add_widget(Label())
        other = BoxLayout()
        self.other_check = CheckBox(active=False,group='majors')
        self.other_label = Label(text='Other')
        other.add_widget(Label())
        other.add_widget(self.other_label)
        other.add_widget(self.other_check)
        other.add_widget(Label())

        options=[ece, meche, roboe, bioe, designe, ec, syse, matscie, other] 
        for choice in options:
            self.majors.add_widget(choice)

        # Export and Save Buttons #
        self.options_bar = BoxLayout(size_hint=(1.0,0.05))        
        self.export_button = Button(text='Export to Spreadsheet',on_press=self.export_user_info)
        self.save_button = Button(text='Save User Information',on_press=self.save_user_info)
        self.options_bar.add_widget(self.export_button)
        self.options_bar.add_widget(self.save_button)       

        # Add Widgets to User Information Half #       
        self.info.add_widget(Label(text='Your Information',font_size = 17,size_hint=(1.0,0.1)))
        self.info.add_widget(self.display_name)
        self.info.add_widget(self.years)
        self.info.add_widget(self.majors)
        self.info.add_widget(self.options_bar)
                

        ## STATS AND NOTES HALF ##
        self.stats_and_notes = BoxLayout(orientation='vertical',size_hint=(0.5,1.0))

        # STATS QUADRANT # 
        self.stats = BoxLayout(orientation='vertical',size_hint=(1.0,0.5))
        # Stats #
        self.information = GridLayout(rows = 3, size_hint = (1.0,0.8))
        self.grad = Label(text='Enough credits to graduate?:  ' + will_grad,size_hint=(1.0,0.4))        
        self.credits = GridLayout(cols=4,rows=2,size_hint=(1.0,0.6))
        self.credits.add_widget (Label())       
        self.credits.add_widget(Label(text = 'AHSE: '+str(self.ahse_cred)))
        self.credits.add_widget(Label(text = 'ENGR: '+str(self.engr_cred)))
        self.credits.add_widget (Label())
        self.credits.add_widget (Label())       
        self.credits.add_widget(Label(text = 'MTH: '+str(self.mth_cred)))
        self.credits.add_widget(Label(text = 'SCI: '+str(self.sci_cred)))
        self.credits.add_widget (Label())  
        self.information.add_widget(self.credits)
        self.information.add_widget(self.grad)

        # Add Widgets to Quadrant #
        self.stats.add_widget(Label(text = 'Credits',font_size = 17,size_hint =(1.0,0.2)))
        self.stats.add_widget(self.information)
        
        # NOTES QUADRANT #        
        self.notes = GridLayout(cols=1,size_hint =(1.0,0.5))
        self.n_label = Label(text='Notes',font_size = 17,size_hint = (1.0,0.15))        
        self.n_entry = TextInput(multiline=True,padding=15,size_hint=(1.0,0.85))              
        self.notes.add_widget(self.n_label)      
        self.notes.add_widget(self.n_entry)

        # Add Stats and Notes to Half #
        self.stats_and_notes.add_widget(self.stats)
        self.stats_and_notes.add_widget(self.notes)


        ## Add Halves to Home Tab ##
        self.add_widget(self.info)       
        self.add_widget(self.stats_and_notes)       

        Clock.schedule_interval(self.update_stats,0.1)

    def update_stats(self,instance):
        """Updates the information displayed on the Home tab and saves info to the user file"""      
        if self.sm.tabs.tabspanel.current_tab == self.sm.tabs.tabspanel.tab1:            
            ahse_cred = all_globals.user.credits['AHSE']         
            engr_cred = all_globals.user.credits['ENGR']
            mth_cred = all_globals.user.credits['MTH']
            sci_cred = all_globals.user.credits['SCI']
            ahse_req = 28
            engr_req = 28
            mth_req = 28
            sci_req = 28      

            ## Add major to user file ##
            if self.ece_check.active == True:           
                all_globals.user.major = self.ece_label.text
            if self.meche_check.active == True:
                all_globals.user.major = self.meche_label.text
            if self.roboe_check.active == True:           
                all_globals.user.major = self.roboe_label.text
            if self.bioe_check.active == True:            
                all_globals.user.major = self.bioe_label.text
            if self.designe_check.active == True:         
                all_globals.user.major = self.designe_label.text
            if self.ec_check.active == True:           
                all_globals.user.major = self.ec_label.text
            if self.syse_check.active == True:            
                all_globals.user.major = self.syse_label.text            
            if self.matscie_check.active == True:            
                all_globals.user.major = self.matscie_label.text
            if self.other_check.active == True:            
                all_globals.user.major = self.other_label.text

            ## Determine if user has enough credits to graduate ##
            if ahse_cred+engr_cred+mth_cred+sci_cred >= 128:
                will_grad = 'Yes'
            else:
                will_grad = 'No' 

            ## Update the displayed credits & name ##
            self.grad.clear_widgets()
            self.grad = Label(text='Enough credits to graduate?:  ' + will_grad)
            self.credits.clear_widgets()
            self.credits.add_widget (Label())
            self.credits.add_widget (Label(text = 'AHSE: '+str(ahse_cred)+' / '+str(ahse_req)))
            self.credits.add_widget (Label(text = 'ENGR: '+str(engr_cred)+' / '+str(engr_req)))
            self.credits.add_widget (Label())
            self.credits.add_widget (Label())
            self.credits.add_widget (Label(text = 'MTH: '+str(mth_cred)+' / '+str(mth_req)))
            self.credits.add_widget (Label(text = 'SCI: '+str(sci_cred)+' / '+str(sci_req)))
            self.credits.add_widget (Label())       
            self.display_name.text = all_globals.user.name
           
            ## Add grad year to user file ##
            if self.year1_check.active == True:
                all_globals.user.grad_year = int(self.year1_label.text)
            elif self.year2_check.active == True:
                all_globals.user.grad_year = int(self.year2_label.text)
            elif self.year3_check.active == True:
                all_globals.user.grad_year = int(self.year3_label.text)
            elif self.year4_check.active == True:
                all_globals.user.grad_year = int(self.year4_label.text)

            ## Add notes to user file ##
            all_globals.user.notes=self.n_entry.text       

    def save_user_info(self,instance):
        #print 'User info saved!'
        all_globals.fm.save_user(all_globals.user)

    def export_user_info(self,instance):
        #print 'User info exported!'
        all_globals.fm.export_user(all_globals.user)
Example #54
0
class StatusBar(BoxLayout):
    '''StatusBar used to display Widget heirarchy of currently selected
       widget and to display messages.
    '''

    app = ObjectProperty()
    '''Reference to current app instance.
       :data:`app` is an
       :class:`~kivy.properties.ObjectProperty`
    '''

    navbar = ObjectProperty()
    '''To be used as parent of :class:`~designer.statusbar.StatusNavBarButton`
       and :class:`~designer.statusbar.StatusNavBarSeparator`.
       :data:`navbar` is an
       :class:`~kivy.properties.ObjectProperty`
    '''

    gridlayout = ObjectProperty()
    '''Parent of :data:`navbar`.
       :data:`gridlayout` is an
       :class:`~kivy.properties.ObjectProperty`
    '''

    playground = ObjectProperty()
    '''Instance of
       :data:`playground` is an
       :class:`~kivy.properties.ObjectProperty`
    '''

    def __init__(self, **kwargs):
        super(StatusBar, self).__init__(**kwargs)
        self.update_navbar = Clock.create_trigger(self._update_navbar)

    def show_message(self, message):
        '''To show a message in StatusBar
        '''

        self.app.widget_focused = None
        if (self.gridlayout.children or not
                isinstance(self.gridlayout.children[0], Label)):
            # Create navbar again, as doing clear_widgets
            # will make its reference
            # count to 0 and it will be destroyed
            self.navbar = GridLayout(rows=1)

        self.gridlayout.clear_widgets()
        self.gridlayout.add_widget(Label(text=message))
        self.gridlayout.children[0].text = message

    def on_app(self, instance, app):
        app.bind(widget_focused=self.update_navbar)

    def _update_navbar(self, *largs):
        '''To update navbar with the parents of currently selected Widget.
        '''

        if self.gridlayout.children and\
                isinstance(self.gridlayout.children[0], Label):
            self.gridlayout.clear_widgets()
            self.gridlayout.add_widget(self.navbar)

        self.navbar.clear_widgets()
        wid = self.app.widget_focused
        if not wid:
            return

        # get parent list, until app.root.playground.root
        children = []
        while wid:
            if wid == self.playground.sandbox or\
                    wid == self.playground.sandbox.children[0]:
                break

            if isinstance(wid, TabbedPanelContent):
                _wid = wid
                wid = wid.parent.current_tab
                children.append(StatusNavBarButton(node=wid))
                wid = _wid.parent

            elif isinstance(wid, TabbedPanelHeader):
                children.append(StatusNavBarButton(node=wid))
                _wid = wid
                while _wid and not isinstance(_wid, TabbedPanel):
                    _wid = _wid.parent
                wid = _wid

            children.append(StatusNavBarButton(node=wid))
            wid = wid.parent

        count = len(children)
        for index, child in enumerate(reversed(children)):
            self.navbar.add_widget(child)
            if index < count - 1:
                self.navbar.add_widget(StatusNavBarSeparator())
            else:
                child.state = 'down'
Example #55
0
class ScreenBankGUI(ScreenBank):
	# Initialize the class.
	def __init__(self, Data):
		#Define window size.
		self.factor = Data.factor
		Config.set('graphics', 'width', Data.factor*800) 
		Config.set('graphics', 'height', Data.factor*600)

		# Create main and middle layout
		self.layout = GridLayout(cols = 1, row_force_default=False, height = 600, width = 800)	
		self.MiddleLayout = GridLayout(cols=1, size_hint_y=11)
		self.MiddleScroll = ScrollView(size_hint=(1, None), size=(Data.factor*400, Data.factor*500), bar_width=4)

		self.settings_json = json.dumps([
		    {'type': 'string',
		     'title': 'Job Manager IP',
		     'desc': 'Address of the JM.',
		     'section': 'example',
		     'key': 'jm_address'},
		    {'type': 'numeric',
		     'title': 'Job Manager Port',
		     'desc': 'Port of the JM.',
		     'section': 'example',
		     'key': 'jm_port'},
		    {'type': 'path',
		     'title': 'Library Path',
		     'desc': 'File with user functions.',
		     'section': 'example',
		     'key': 'lib_path'},
		    {'type': 'numeric',
		     'title': 'Number of Tasks',
		     'desc': 'Amount of work to be done.',
		     'section': 'example',
		     'key': 'num_tasks'}])

		self.settings_json2 = json.dumps([
		   {'type': 'string',
		     'title': 'Virtual Machine IP',
		     'desc': 'Address of the Virtual Machine TM.',
		     'section': 'example',
		     'key': 'vm_ip'},
		   {'type': 'string',
		     'title': 'Virtual Machine Port',
		     'desc': 'Port of the Virtual Machine TM.',
		     'section': 'example',
		     'key': 'vm_prt'}, 
		   {'type': 'string',
		     'title': 'SSH Login',
		     'desc': 'Used to log in Virtual Machine TM.',
		     'section': 'example',
		     'key': 'ssh_login'},
		   {'type': 'string',
		     'title': 'SSH Password',
		     'desc': 'Look behind you before typing.',
		     'section': 'example',
		     'key': 'ssh_pass'}])

		self.settings_json3 = json.dumps([
		   {'type': 'bool',
		     'title': 'SSH Port Fowarding',
		     'desc': 'Activate/Deactivate for connecting with Job Manager',
		     'section': 'example',
		     'key': 'ssh_pf_bool'},
		   {'type': 'string',
		     'title': 'SSH Login',
		     'desc': 'Username used in SSH connection.',
		     'section': 'example',
		     'key': 'ssh_pf_login'}, 
		   {'type': 'string',
		     'title': 'SSH Password',
		     'desc': 'Look behind you before typing.',
		     'section': 'example',
		     'key': 'ssh_pf_pass'}])

		self.settings_json4 = json.dumps([
		   {'type': 'string',
		     'title': 'Subscription ID',
		     'desc': 'ID obtained in Azure.',
		     'section': 'example',
		     'key': 'subscription_id'}, 
		   {'type': 'path',
		     'title': 'Certificate Path',
		     'desc': 'Location of the path sent to Azure.',
		     'section': 'example',
		     'key': 'certificate_path'}])

		# Layout that represents the list.
		self.ListLayout = GridLayout(cols=len(Data.columns), row_default_height=Data.factor*30, row_force_default = True, rows=(Data.npp + 1) , size_hint_y=10)
		self.NavigationLayout = GridLayout(cols=2, row_default_height=Data.factor*15)

		# Layout that represents the VMlist..
		self.VMListLayout = GridLayout(cols=len(Data.VMcolumns), row_default_height=Data.factor*30, row_force_default = True, rows=(Data.npp + 1) , size_hint_y=10)
		self.VMNavigationLayout = GridLayout(cols=2, row_default_height=Data.factor*15)

		# Layout that represents the log
		self.LogWidget = TextInput(multiline=True)

		# Layout that represents the main Header
		self.HeaderLayout = GridLayout(cols=7, row_default_height=Data.factor*15)

		# Name of current screen
		self.ScreenName = "List"

		# Task FIFOs
		self.workerFIFO = FIFO()
		self.mainFIFO = FIFO()

		#Extra Thread
		self.WorkerThread = threading.Thread(target=self.worker)
		self.WorkerThread.start()

		# Set consume as callback function
		Clock.schedule_interval(self.consume, 0.1)

	# Worker function.
	def worker(self):
		print 'worker'
		while(self.workerFIFO.task_end == False):		# Check if it's over.
			self.workerFIFO.pendent_tasks.acquire()		# Wait for tasks
			task = self.workerFIFO.popTask()		# Pop task
			self.workerFIFO.runOneTask(task)		# Run the task

		print 'Worker exited.'
		return

	# Function to kill/remove worker from tasks FIFO and exit.
	def quitWorker(self):
		self.workerFIFO.task_end = True				# Mark as ended.
		self.workerFIFO.task_FIFO_mutex.acquire()		# Add empty task
		self.workerFIFO.task_FIFO.append([1, None, []])
		self.workerFIFO.task_FIFO_mutex.release()
		self.workerFIFO.pendent_tasks.release()			# Release, it may be stopped

	def consume(self, *args):
		while (self.mainFIFO.tasks_in_FIFO > 0): 
			task = self.mainFIFO.popTask()
			print 'Consuming:' + str(task)
			self.mainFIFO.runOneTask(task)

	# Build the main screen, with header, list, navigation and command.
	def buildMainScreen(self, Data):
		# Make header layout and add to the main.
		self.makeHeaderLayout()
		self.layout.add_widget(self.HeaderLayout)

		# Make list rows and add it to the middle layout 
		self.MiddleLayout.add_widget(self.ListLayout)

		# Build list screen and add Middle Layout to the main layout.
		self.buildListScreen()
		self.layout.add_widget(self.MiddleLayout)

		# Make Console Layout and add it to the main layout 
		self.CommandLayout = GridLayout(cols=1, row_default_height=Data.factor*30, row_force_default=True)
		self.makeCommandLayout(Data, 'Welcome to SPITZ Monitor')
		self.layout.add_widget(self.CommandLayout)

		self.reDrawList(Data)

	# Build the list screen, just updating the middle layout.
	def buildListScreen(self):
		self.MiddleLayout.clear_widgets()
		self.MiddleLayout.add_widget(self.ListLayout)
		self.MiddleLayout.add_widget(self.NavigationLayout)

	# Build the list screen, just updating the middle layout.
	def buildVMListScreen(self):
		self.MiddleLayout.clear_widgets()
		self.MiddleLayout.add_widget(self.VMListLayout)
		self.MiddleLayout.add_widget(self.VMNavigationLayout)

	# Build the log screen, just updating the middle layout.
	def buildLogScreen(self):
		self.MiddleLayout.clear_widgets()
		self.MiddleScroll.clear_widgets()
		self.LogWidget.size_hint_y = None
		self.LogWidget.height = max( (len(self.LogWidget._lines)+1) * self.LogWidget.line_height, self.MiddleScroll.size[1])
		self.MiddleScroll.do_scroll_x = False
		self.MiddleScroll.add_widget(self.LogWidget)
		self.MiddleLayout.add_widget(self.MiddleScroll)

	# Build the Settings screen.
	def buildSettingsScreen(self):
		Runner.MyApp.open_settings(self.AppInstance)
		#self.layout.add_widget(self.sett)

	# Makes the layout of the list, adding the columns name, the ordering handlers and the actual page.
	def makeListLayout(self, Data):	
		layout = self.ListLayout
		layout.clear_widgets()
		for col in range(len(Data.columns)):
			btnO = Button(text=Data.columns[col], size_hint_x=None, width=Data.wid[col])
			btnO.bind(on_press=buttonOrder)
			layout.add_widget(btnO)
		
		upper = min(len(Data.rows), (Data.index + 1)*Data.npp)
		#print "upper: "+str(upper)
		for i in range(Data.index*Data.npp, upper):
			for j in range(len(Data.wid)):
				layout.add_widget(Button(text=str(Data.rows[i][j]), size_hint_x=None, width=Data.wid[j]))
		self.ListLayout = layout

	# Makes the buttons to navigate. Add the handler and text if there is any.
	def makeNavigationLayout(self, Data):
		layout = self.NavigationLayout
		layout.clear_widgets()
		if(Data.index > 0):
			btnP = Button(text="Previous", size_hint_x=None, width = Data.factor*400)
			btnP.bind(on_press = buttonPrev)
			layout.add_widget(btnP)
		else:
			layout.add_widget(Button(text="", size_hint_x=None, width = Data.factor*400))

		if(len(Data.rows)>(Data.index + 1)*Data.npp):
			btnN = Button(text="Next", size_hint_x=None, width = Data.factor*400)
			btnN.bind(on_press = buttonNext)
			layout.add_widget(btnN)
		else:
			layout.add_widget(Button(text="", size_hint_x=None, width = Data.factor*400))
		self.NavigationLayout = layout

	# Makes the layout of the VM list, adding the columns name, the ordering handlers and the actual page.
	def makeVMListLayout(self, Data):	
		layout = self.VMListLayout
		layout.clear_widgets()
		for col in range(len(Data.VMcolumns)):
			btnO = Button(text=Data.VMcolumns[col], size_hint_x=None, width=Data.VMwid[col])
			btnO.bind(on_press=buttonVMOrder)
			layout.add_widget(btnO)
		
		upper = min(len(Data.VMrows), (Data.index + 1)*Data.npp)
		#print "upper: "+str(upper)
		for i in range(Data.index*Data.npp, upper):
			# Create buttons. Actions buttons has actions.
			for j in range(len(Data.VMwid)):
				if j == len(Data.VMwid)-1:
					# Button responsible for VM action, as it has different index and action, calls partial functions.
					btnA = Button(text=str(Data.VMrows[i][len(Data.VMwid)-1]), size_hint_x=None, width=Data.VMwid[-1])
					btnA.bind(on_press=partial(buttonSpitzAction, i, btnA.text))
					layout.add_widget(btnA)

				elif j == len(Data.VMwid)-3:
					# Button responsible for VM action, as it has different index and action, calls partial functions.
					btnA = Button(text=str(Data.VMrows[i][len(Data.VMwid)-3]), size_hint_x=None, width=Data.VMwid[-3])
					btnA.bind(on_press=partial(buttonAzureAction, i, btnA.text))
					layout.add_widget(btnA)

				else:
					layout.add_widget(Button(text=str(Data.VMrows[i][j]), size_hint_x=None, width=Data.VMwid[j]))


		self.VMListLayout = layout

	# Makes the buttons to navigate the VM list. Add the handler and text if there is any.
	def makeVMNavigationLayout(self, Data):
		layout = self.VMNavigationLayout
		layout.clear_widgets()
		if(Data.index > 0):
			btnP = Button(text="Previous", size_hint_x=None, width = Data.factor*400)
			btnP.bind(on_press = VMbuttonPrev)
			layout.add_widget(btnP)
		else:
			layout.add_widget(Button(text="", size_hint_x=None, width = Data.factor*400))

		if(len(Data.rows)>(Data.index + 1)*Data.npp):
			btnN = Button(text="Next", size_hint_x=None, width = Data.factor*400)
			btnN.bind(on_press = VMbuttonNext)
			layout.add_widget(btnN)
		else:
			layout.add_widget(Button(text="", size_hint_x=None, width = Data.factor*400))
		self.VMNavigationLayout = layout

	# Makes the header layout, with the commands.
	def makeHeaderLayout(self):
		layout = self.HeaderLayout
		layout.clear_widgets()

		self.btnP = Button(text="Update", size_hint_x=None, width = self.factor*125)
		self.btnP.bind(on_press = buttonUpdate)
		layout.add_widget(self.btnP)

		btnSep = Button(text="", size_hint_x=None, width = self.factor*50)
		layout.add_widget(btnSep)

		self.btnLi = ToggleButton(text="List", group='menu', size_hint_x=None, width = self.factor*125, state='down')
		self.btnLi.bind(on_press = buttonList)
		layout.add_widget(self.btnLi)

		self.btnV = ToggleButton(text="VM Launcher", group='menu', size_hint_x=None, width = self.factor*125)
		self.btnV.bind(on_press = buttonVM)
		layout.add_widget(self.btnV)

		self.btnSta = ToggleButton(text="Statistics", group='menu', size_hint_x=None, width = self.factor*125)
		self.btnSta.bind(on_press = buttonStatistics)
		layout.add_widget(self.btnSta)

		self.btnL = ToggleButton(text="Log", group='menu', size_hint_x=None, width = self.factor*125)
		self.btnL.bind(on_press = buttonLog)
		layout.add_widget(self.btnL)

		self.btnS = Button(text="Settings", size_hint_x=None, width = self.factor*125)
		self.btnS.bind(on_press = buttonSettings)
		layout.add_widget(self.btnS)

	def makeCommandLayout(self, Data, itext):
		layout = self.CommandLayout
		layout.clear_widgets()
		self.commandWidget = TextInput(multiline=False)
		self.commandWidget.readonly = True	
		self.commandWidget.text = itext

		pb = ProgressBar(max=1000)	
		pb.value = (Data.total_compl*1000)/(int(Data.TotalTasks))

		layout.add_widget(self.commandWidget)
		layout.add_widget(pb)
	
		#Get current time and add the message to the log pile.	
		logmessage = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
		logmessage = logmessage + " >>> " + itext 
		Data.log = Data.log + "\n" + logmessage

	# Redraw list using current values of nodes.	
	def reDrawList(self, Data):
		self.makeListLayout(Data)
		self.makeNavigationLayout(Data)

	def makeLogLayout(self, Data):
		self.LogWidget.readonly = True
		self.LogWidget.text = Data.log

	def screenChange(self, value, name):
		self.ScreenName = name
		if(value.state == 'normal'):
			value.state = 'down' 
class MoonboardAppLayout(GridLayout):


    def __init__(self, **kwargs):
        super(MoonboardAppLayout, self).__init__(**kwargs)
        # self.moonImagesArray = [None] * 228
        self.cols = 2
        self.rows = 2
        self.db = DbCon()
        global Routes, problemButton, filterBox, FilterLabel, filteredCommandStr, orderCommandStr, pageIndex, screen1, screen2
        #filteredCommandStr = " WHERE (GradeUS = 'V4+' OR GradeUS = 'V5' OR GradeUS = 'V5+' OR GradeUS = 'V6' OR GradeUS = 'V7' OR GradeUS = 'V8' OR GradeUS = 'V8+' OR GradeUS = 'V9' OR GradeUS = 'V10' OR GradeUS = 'V11' OR GradeUS = 'V12' OR GradeUS = 'V13' OR GradeUS = 'V14') AND (Stars = 0 OR Stars = 1 OR Stars = 2 OR Stars = 3) ORDER BY DateAdded ASC LIMIT 0,100"
        filteredCommandStr = ""
        orderCommandStr = "ORDER BY RAND() "
        pageIndex = 0
        Routes = self.db.get_rows()
        problemButton = [None] * len(Routes)
        filterBox = [None] * 20
        FilterLabel = [None] * 19
        filterBox[19] = False
        self.moonImages = [None] * 240
        self.problemList = GridLayout(cols=1, size_hint_y=None)
        self.problemList.bind(minimum_height=self.problemList.setter('height'))
        toggleText = ["6B+/V4+", "6C/V5", "6C+/V5+", "7A/V6", "7A+/V7", "7B/V8", "7B+/V8+", "7C/V9", "7C+/V10", "8A/V11", "8A+/V12", "8B/V13", "8B+/V14", "3 Stars",
                      "2 Stars", "1 Star", "0 Stars", "Popular", "Newest"]
        for i in range(len(Routes)):
        #for i in range(10):
            problemButton[i] = Problem(
                text=str(Routes[i][0] + '\n' + "Set By: " + Routes[i][1]) + '\n' + "Grade: " + Routes[i][2] + '/' +
                     Routes[i][3] + " Stars: " + str(Routes[i][4]) + '\n' + "Moves: " + str(Routes[i][5]) + '     ' + "Repeats: " + str(Routes[i][6]),
                size_hint_y=None)
            problemButton[i].route = Routes[i][7:211]
            problemButton[i].routeName = str(Routes[i][0])
            problemButton[i].setterName = str(Routes[i][1])
            problemButton[i].gradeUK = str(Routes[i][2])
            problemButton[i].gradeUS = str(Routes[i][3])
            problemButton[i].stars = Routes[i][4]
            problemButton[i].moves = Routes[i][5]
            problemButton[i].repeats = Routes[i][6]
            self.problemList.add_widget(problemButton[i])
        self.moonImageGroup = moonBoardProblemImage()
        self.temp = 0
        for i in range(19):
            for j in range(12):
                self.imageStr = str("images/moon-" + str(i) + "-" + str(j) + ".png")
                global LED_ROUTE_IMAGES
                LED_ROUTE_IMAGES[self.temp] = moonBoardImage(source=self.imageStr, size_hint_y=1, size_hint_x=1,
                                                             allow_stretch=True, keep_ratio=False)
                # self.moonImagesArray[temp]
                self.temp += 1
        for i in range(228):
            self.moonImageGroup.add_widget(LED_ROUTE_IMAGES[i])

        self.moonboardProblemsScroll = ScrollView()
        self.search_field = BoxLayout()
        self.navigation_field = BoxLayout()
        self.customizeBox = GridLayout(cols=1, size_hint_y=None)
        self.search_input = TextInput(text="", multiline=False)
        self.search_button = SearchButton(text="search", on_press=self.search)
        self.next_page_button = Button(text=">", on_press=self.pageIncrease)
        self.random_button = Button(text="Random", on_press=self.randomPressed)
        self.prev_page_button = Button(text="<", on_press=self.pageDecrease)
        self.customize = Button(text="Create Your Own!", on_press=screen1.changer)
        #self.nextPage = SearchButton(text="search", on_press=self.search)
        self.searchGrid = GridLayout(cols=1)
        self.navigateGrid = GridLayout(rows=2, orientation="vertical", size_hint_y=None)
        self.filterGroup = GridLayout(cols=4)

        self.moonboardProblemsScroll.add_widget(self.problemList)
        self.add_widget(self.moonboardProblemsScroll)
        for i in range(len(toggleText)):

            if toggleText[i] == "Popular":
                print("FALSE CHECKBOX")
                filterBox[i] = FilterBox(on_press=self.filter, active=False)
            elif toggleText[i] == "Newest":
                print("FALSE CHECKBOX")
                filterBox[i] = FilterBox(on_press=self.filter, active=True)
            else:
                filterBox[i] = FilterBox(on_press=self.filter, active=True)
            # print(filterBox[i])
            # lastFilterBox[i] = filterBox[i]
            FilterLabel[i] = Label()
            FilterLabel[i].text = toggleText[i]
            self.filterGroup.add_widget(filterBox[i])
            self.filterGroup.add_widget(FilterLabel[i])
        self.searchGrid.add_widget(self.filterGroup)
        self.searchGrid.add_widget(self.moonImageGroup)
        self.search_field.add_widget(self.search_input)
        self.search_field.add_widget(self.search_button)
        self.navigation_field.add_widget(self.prev_page_button)
        self.navigation_field.add_widget(self.random_button)
        self.navigation_field.add_widget(self.next_page_button)
        self.navigateGrid.add_widget(self.search_field)
        self.navigateGrid.add_widget(self.navigation_field)
        self.customizeBox.add_widget(self.customize)
        self.add_widget(self.searchGrid)
        self.add_widget(self.navigateGrid)
        self.add_widget(self.customizeBox)

        #self.add_widget(self.nextPage)


        # self.moonImagesArray[13].source = "images/moon-1-1-blue-square.png"
        # self.moonImagesArray[14].source = "images/moon-1-1-blue-square.png"
        # self.moonImagesArray.reload()
    def randomPressed(self, random):

        global filterBox, pageIndex
        if filterBox[19] == False:
            filterBox[19] = True
        pageIndex = 0

        self.filter()

    def dump(obj, *args):
        for attr in dir(obj):
            print("obj.%s = %s" % (attr, getattr(obj, attr)))


    def pageIncrease(self, pageNum):  #TODO account for something like remaining 99 if there isn't an even search
        global Routes, pageIndex, filterBox
        print(pageIndex)
        print(len(Routes))
        filterBox[19] = False
        if (len(Routes) > 99):
            pageIndex+=1
        else:
            pageIndex+=0
        self.filter()


    def pageDecrease(self, pageNum):  #TODO account for something like remaining 99 if there isn't an even search
        global Routes, pageIndex, filterBox
        print(pageIndex)
        print(len(Routes))

        filterBox[19] = False
        if (pageIndex > 0):
            pageIndex-=1
        else:
            pageIndex+=0
        self.filter()

    def creationScreen(self):
        self.clear_widgets()

    def filter_table(self, search=""):
        global Routes, filterBox, pageIndex
        # if filterBox[17].active or filterBox[18].active:
        #     filterBox[19] = False
        if filterBox[19]:
            filterBox[17].active = False
            filterBox[18].active = False

        #Routes = self.db.get_rows_filtered(filterBox[0].active, filterBox[1].active, filterBox[2].active, filterBox[3].active, filterBox[4].active, filterBox[5].active, filterBox[6].active, filterBox[7].active, filterBox[8].active, filterBox[9].active, filterBox[10].active, filterBox[11].active, filterBox[12].active, filterBox[13].active, filterBox[14].active, filterBox[15].active, filterBox[16].active, filterBox[17].active, filterBox[18].active, filterBox[19].active, search)
        Routes = self.db.get_rows_filtered(filterBox[0].active, filterBox[1].active, filterBox[2].active,
                                           filterBox[3].active, filterBox[4].active, filterBox[5].active,
                                           filterBox[6].active, filterBox[7].active, filterBox[8].active,
                                           filterBox[9].active, filterBox[10].active, filterBox[11].active,
                                           filterBox[12].active, filterBox[13].active, filterBox[14].active,
                                           filterBox[15].active, filterBox[16].active, filterBox[17].active,
                                           filterBox[18].active, filterBox[19], search)
        for index in range(len(Routes)):
            #print(Routes[index])
            #print(len(Routes[index]))
            problemButton[index] = Problem(
                text=str(Routes[index][0] + '\n' + "Set By: " + Routes[index][1]) + '\n' + "Grade: " + Routes[index][2] + '/' +
                     Routes[index][3] + " Stars: " + str(Routes[index][4]) + '\n' + "Moves: " + str(Routes[index][5]) + '     ' + "Repeats: " + str(Routes[index][6]),
                size_hint_y=None)
            problemButton[index].route = Routes[index][7:211]
            problemButton[index].routeName = str(Routes[index][0])
            problemButton[index].setterName = str(Routes[index][1])
            problemButton[index].gradeUK = str(Routes[index][2])
            problemButton[index].gradeUS = str(Routes[index][3])
            problemButton[index].stars = Routes[index][4]
            problemButton[index].moves = Routes[index][5]
            problemButton[index].repeats = Routes[index][6]
            self.problemList.add_widget(problemButton[index])


    def update_table(self, search=""):
        global Routes
        Routes = self.db.get_rows_searched(search)
        #print(Routes)
        for index in range(len(Routes)):
            #print(Routes[index])
            #print(len(Routes[index]))
            problemButton[index] = Problem(
                text=str(Routes[index][0] + '\n' + "Set By: " + Routes[index][1]) + '\n' + "Grade: " + Routes[index][2] + '/' +
                     Routes[index][3] + " Stars: " + str(Routes[index][4]) + '\n' + "Moves: " + str(Routes[index][5]) + '     ' + "Repeats: " + str(Routes[index][6]),
                size_hint_y=None)
            problemButton[index].route = Routes[index][7:211]
            problemButton[index].routeName = str(Routes[index][0])
            problemButton[index].setterName = str(Routes[index][1])# -*- coding: utf-8 -*-
            problemButton[index].gradeUK = str(Routes[index][2])
            problemButton[index].gradeUS = str(Routes[index][3])
            problemButton[index].stars = Routes[index][4]
            problemButton[index].moves = Routes[index][5]
            problemButton[index].repeats = Routes[index][6]
            self.problemList.add_widget(problemButton[index])

    def clear_table(self):
        self.problemList.clear_widgets()

    def search(self, *args):
        self.clear_table()
        self.update_table(self.search_input.text)

    def filter(self, *args):
        self.clear_table()
        self.filter_table(self.search_input.text)

    def changer(self, *args):
        self.manager.current = 'screen1'
Example #57
0
class GUI(BoxLayout):
    """This class is devoted to create GUI and handle the actions"""

    
    #variable for converter class
    converter = None
    
    loadfile = ObjectProperty(None)
    selected_file = None
    path = None
    path_only = None
    lgf_name = None
    lgf_nfo = None
    
    node_params_root = None
    node_params_layout = None
    edge_params_root = None
    edge_params_layout = None
    
    
    params_width = Window.width/2
    params_height = Window.height/2.6
    
    
    
    #GUI node_params dictionary for the found node params list
    #by means of this, we can easily check after clicking Convert button that what should be
    #written in the lemon file and how
    node_params_to_write = dict()
    #and the same for edges
    edge_params_to_write = dict()
    
    
    #link costs' checkbox
    found_cost_cb = None
    random_cost_cb = None
    unit_cost_cb = None
    
    symmetric_cost_cb = None
    
    #convert button
#     convert_button = None
    lemon_req = "USE AS LEMON REQUIRES"
    
    def initialize(self):
        '''
        INITIALIZING GUI COMPONENTS
        '''
        #just for faster testing
        self.file_text_input.text = ""
     
        #initializing node_params scrollview and layout
        self.node_params_layout = GridLayout(cols=2,spacing=10, size_hint_y=None)
        self.node_params_layout.bind(minimum_height=self.node_params_layout.setter('height'))
        
        self.node_params_root = ScrollView(size_hint=(None, None), 
                                           size=(self.params_width,self.params_height),
                                           bar_width=5,
                                           bar_color=[.3,.3,.9,.5],
                                           do_scroll_x=False,
                                           )        
        self.node_params_root.add_widget(self.node_params_layout)
        #initializing edge_params scrollview and layout
        self.edge_params_layout = GridLayout(cols=2,spacing=10,size_hint_y=None)
        self.edge_params_layout.bind(minimum_height=self.edge_params_layout.setter('height'))
        self.edge_params_root = ScrollView(size_hint=(None, None), 
                                           size=(self.params_width-20,self.params_height),
                                           bar_width=5,
                                           bar_color=[.3,.3,.9,.5],
                                           do_scroll_x=False)        
        self.edge_params_root.add_widget(self.edge_params_layout)
        
        #adding params widgets
        self.params_boxlayout.add_widget(self.node_params_root)
        self.params_boxlayout.add_widget(self.edge_params_root)

        
        
    
    def dismiss_popup(self):
        """
        This dismisses popups
        """
        self._popup.dismiss()
    
    
    def show_load(self):
        """
        show load file dialog
        """
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file", content=content, size_hint=(0.9, 0.9))
        self._popup.open()
    
    
    def load(self, path, filename):
        """
        this will load the file and dismiss the dialog
        """

        try:
            self.selected_file = filename[0]
            self.file_text_input.text = self.selected_file
            self.dismiss_popup()
#             print "Selected file",self.selected_file
            #getting the path and the filename separately
            
            basename = os.path.basename(self.selected_file) 
            path = os.path.abspath((self.selected_file))
            
#             print "Basename",basename
            self.path_only = path[:(len(path)-len(basename))]
            basename = str(os.path.splitext(os.path.basename(self.selected_file))[0])
            #With these variable will shown where the new lgf and nfo file is saved
            self.lgf_name = self.path_only + basename  + ".lgf"
            self.lgf_nfo = self.path_only + basename + ".nfo"
            
            
#             print self.path_only
#             print self.lgf_name
#             print self.lgf_nfo
            
        except IndexError as ie:
            print ("Something made a boo-boo...try again", str(ie))  
            self.dismiss_popup()
            self.show_popup("ERROR","Somehow I couldn't load the file:\nCheck the permissions or move it to other place")
        
         
    def analyze(self):
        '''
        This function analyzes the read gml file
        '''
        self.converter = Converter(self.file_text_input.text)
        self.converter.set_reference(self.console_log)
        
        #clear console log
        self.console_log.text = ""
        #check that selected file is existing
        if(self.converter.read_file() != False):
            
            self.node_param_label.text = "Found node params (#{})".format(str(len(self.converter.node_params)))
            self.edge_param_label.text = "Found edge params (#{})".format(str(len(self.converter.edge_params)))
            
           
            
            #removing previously added widgets
            self.node_params_layout.clear_widgets()
            self.edge_params_layout.clear_widgets()
            
            
            ##### ---=========== NODE PARAMS PART    =====------- ######
            #adding the two column names
            self.node_params_layout.add_widget(Label(text="", font_size="12sp"))
            self.node_params_layout.add_widget(Label(text="", font_size="12sp"))
            self.node_params_layout.add_widget(Label(text="Property name in [b]GML[/b]", font_size="14sp",markup=True))
            self.node_params_layout.add_widget(Label(text="Property name in [b]LGF[/b]", font_size="14sp",markup=True))
            
            
            
            
            #adding found paramters to the related params widgets
            for i in self.converter.node_params:
                #LEMON uses label for ids
                if(str(i) == "id"):
                    textinput = TextInput(text = "label", 
                                          multiline=False,
                                          size_hint_x=0.6, 
                                          size_hint_y=None, 
                                          height=28, 
                                          font_size=12,
                                          readonly=True,
                                          foreground_color=[.9,.1,.1,1],
                                          background_color=[.7,.7,.7,1])
                elif(str(i) == "label"):
                    textinput = TextInput(text = "name", 
                                          multiline=False,
                                          size_hint_x=0.6, 
                                          size_hint_y=None, 
                                          height=28, 
                                          font_size=12,
                                          readonly=True,
                                          foreground_color=[.9,.1,.1,1],
                                          background_color=[.7,.7,.7,1])
                else:
                    textinput = TextInput(text = str(i).lower(), 
                                          multiline=False,
                                          size_hint_x=0.6, 
                                          size_hint_y=None, 
                                          height=28, 
                                          font_size=12)
                
                self.node_params_to_write[str(i)]=textinput
              
#             print(self.node_params_to_write)  
            for i in self.node_params_to_write:       
                if(self.converter.node_params[i] != len(self.converter.nodes)):          
                    label_text = "[b][color=ffff00]"+str(i) + "[/color][/b] --->"
                else:
                    label_text = "[b]"+str(i) + "[/b] --->"
                label = Label(text=label_text,
                              size_hint_x=0.4, 
                              size_hint_y=None, 
                              height=28, 
                              font_size="12sp",
                              markup=True)
                self.node_params_layout.add_widget(label)
                self.node_params_layout.add_widget(self.node_params_to_write[i])
            ##### ---======= END OF NODE PARAMS PART =====------- ######
        
        
        
        
        
            ##### ---=========== EDGE PARAMS PART    =====------- ######
            #adding the two column names
            self.edge_params_layout.add_widget(Label(text="", font_size="12sp"))
            self.edge_params_layout.add_widget(Label(text="", font_size="12sp"))
            self.edge_params_layout.add_widget(Label(text="Property name in [b]GML[/b]", font_size="14sp",markup=True))
            self.edge_params_layout.add_widget(Label(text="Property name in [b]LGF[/b]", font_size="14sp",markup=True))

            #adding found paramters to the related params widgets
            for i in self.converter.edge_params:
                #LEMON uses label for ids
                if((str(i) == "source") or (str(i) == "target")):
                    textinput = TextInput(text = self.lemon_req, 
                                          multiline=False,
                                          size_hint_x=0.6, 
                                          size_hint_y=None, 
                                          height=28, 
                                          font_size=12,
                                          readonly=True,
                                          foreground_color=[.9,.1,.1,1],
                                          background_color=[.7,.7,.7,1])
                elif((str(i) == "id") or (str(i) == "label")):
                    textinput = TextInput(text = "name", 
                                          multiline=False,
                                          size_hint_x=0.6, 
                                          size_hint_y=None, 
                                          height=28, 
                                          font_size=12)
                else:
                    textinput = TextInput(text = str(i).lower(), 
                                          multiline=False,
                                          size_hint_x=0.6, 
                                          size_hint_y=None, 
                                          height=28, 
                                          font_size=12)
                    
                self.edge_params_to_write[str(i)]=textinput
            for i in self.edge_params_to_write:       
                if(self.converter.edge_params[i] != len(self.converter.edges)):          
                    label_text = "[b][color=ffff00]"+str(i) + "[/color][/b] --->"
                else:
                    label_text = "[b]" + str(i) + "[/b] --->"
                label = Label(text=label_text,
                              size_hint_x=0.4, 
                              size_hint_y=None, 
                              height=28, 
                              font_size="12sp",
                              markup=True)
                self.edge_params_layout.add_widget(label)
                self.edge_params_layout.add_widget(self.edge_params_to_write[i])
            
            
            #adding checkboxes for link costs                        
            self.found_cost_cb = CheckBox(size_hint=(.9,None),group="link_costs",height=12,active=True)
#             found_cost_cb.bind(active=self.on_checkbox_active)
            self.random_cost_cb = CheckBox(size_hint=(.9,None),group="link_costs",height=12)
#             random_cost_cb.bind(active=self.on_checkbox_active)
            self.unit_cost_cb = CheckBox(size_hint=(.9,None),group="link_costs",height=12)
#             unit_cost_cb.bind(active=self.on_checkbox_active)
            
           
            #adding checkboxes to GUI
            self.edge_params_layout.add_widget(Label(text="Found link costs",halign="justify"))
            self.edge_params_layout.add_widget(self.found_cost_cb)
            self.edge_params_layout.add_widget(Label(text="Random[1,100] link costs",halign="justify"))
            self.edge_params_layout.add_widget(self.random_cost_cb)
            self.edge_params_layout.add_widget(Label(text="Unit link costs",halign="justify"))
            self.edge_params_layout.add_widget(self.unit_cost_cb)
            
            
            #adding symmetric link costs option to GUI
            self.symmetric_cost_cb = CheckBox(size_hint=(.9,None),height=14,paddint=10,active=True)
            self.edge_params_layout.add_widget(Label(text="", font_size="14sp"))
            self.edge_params_layout.add_widget(Label(text="", font_size="14sp"))
            self.edge_params_layout.add_widget(Label(text="Use symmetric costs"))
            self.edge_params_layout.add_widget(self.symmetric_cost_cb)
#             self.edge_params_layout.add_widget(Label(text="(Lemon DiGraph)",size_hint=(None,None),height=8))
            
            
            ##### ---======= END OF EDGE PARAMS PART =====------- ######
#           
    
        else:
#             self.show_popup("ERROR", "Unable to read file: {}".format(self.file_text_input.text))
            self.show_popup("ERROR", self.converter.error_msg)

#     def on_checkbox_active(self,checkbox,value):
#         
#         print value

    def dummy(self):
        print("GML2LGF converter gui started")
        
        
    def convert(self):
        """This function checks whether everything was set and read correctly,
        and then calls Converter class' dedicated functions to write out
        the new LGF file"""
        
        #checking that analyze button was pressed and some gml file was already loaded  
        if isinstance(self.converter, Converter):
            #OK, we can do convert now, all necessary stuff was created and file was read
            
            status = dict()
            print ("CONVERT")     
            if(self.found_cost_cb.active):
                status["cost"] = "found"
            elif(self.random_cost_cb.active):
                status["cost"] = "random"   
            elif(self.unit_cost_cb.active):
                status["cost"] = "unit"
            else:
                self.show_popup("ERROR", "Somehow the type of costs was not selected")    
             
            status["symmetric"] = False
            if(self.symmetric_cost_cb.active):
                   status["symmetric"] = True
                
            #HERE we call the Converter class' function to finalize the results
            node_params_to_write_with_given_paramname = dict()
            for i in self.node_params_to_write:
                if(self.node_params_to_write[i].text != ""):
                    node_params_to_write_with_given_paramname[i] = self.node_params_to_write[i].text
                    
            
            #HERE we get the set parameters for the edges
            edge_params_to_write_with_given_paramname = dict()
            for i in self.edge_params_to_write:
                if(self.edge_params_to_write[i].text != self.lemon_req):
                    edge_params_to_write_with_given_paramname[i] = self.edge_params_to_write[i].text
                
            self.converter.write_out_results(status,
                                             node_params_to_write_with_given_paramname,
                                             edge_params_to_write_with_given_paramname)
            
        
            self.show_popup("DONE","The new .lgf and .nfo file is created\n"+str(self.lgf_name)+"\n"+str(self.lgf_nfo))
#             print "The new .lgf and .nfo file is created\n"+str(self.lgf_name)+"\n"+str(self.lgf_nfo)
        else:
            print ("No file was loaded and analyze --- do it first")
            self.show_popup("ERROR", "No GML file was loaded and analyzed\n DO IT FIRST!")
         
        
            
        
    def show_popup(self,*args):
        """This functions shows a Kivy Popup window"""
        
        popup = Popup(title=args[0],
                      content=Label(text=args[1]),
                      size_hint=(None,None), 
                      size=(Window.width-50,Window.height-50),
                      separator_color=[247 / 255., 1 / 255., 1 / 255., 1.],
                      title_size='24sp')
        popup.open()
        

    def get_filetext_input(self):
        """reads the text of the file input text_field"""
        return self.file_txt_input
    
    
    def close(self):
        """Default close event to main window"""
        exit()
Example #58
0
class Menu(Widget):
    def __init__(self, **kwargs):
        super(Menu, self).__init__(**kwargs)
        self.loaded = False
        self.first = True

        self.grid = GridLayout(
            cols=1, pos=(self.x, self.y), col_default_width=button_size[0], row_default_height=button_size[1]
        )
        self.add_widget(self.grid)

        # Preload
        self.play = Button(
            text="- Play",
            font_name="fonts/bradley.TTF",
            halign="left",
            color=(0, 0, 0, 1),
            size=button_size,
            text_size=button_size,
            font_size=font_size,
            background_color=(0, 0, 0, 0),
        )
        self.play.bind(on_release=self.button_up)
        self.play.bind(on_press=self.button_down)
        self.play.bind(on_release=self.show_play)

        self.settings = Button(
            text="- Settings",
            font_name="fonts/bradley.TTF",
            color=(0, 0, 0, 1),
            size=button_size,
            text_size=button_size,
            font_size=font_size,
            background_color=(0, 0, 0, 0),
        )
        self.settings.bind(on_release=self.button_up)
        self.settings.bind(on_press=self.button_down)
        self.settings.bind(on_release=self.show_settings)

        self.var1 = Button(
            text="- Variante1",
            font_name="fonts/bradley.TTF",
            color=(0, 0, 0, 1),
            size=button_size,
            text_size=button_size,
            font_size=font_size_small,
            background_color=(0, 0, 0, 0),
        )
        self.var1.bind(on_release=self.button_up)
        self.var1.bind(on_press=self.button_down)
        self.var1.bind(on_release=self.play_var1)

        self.var2 = Button(
            text="- Variante2",
            font_name="fonts/bradley.TTF",
            color=(0, 0, 0, 1),
            size=button_size,
            text_size=button_size,
            font_size=font_size_small,
            background_color=(0, 0, 0, 0),
        )
        self.var2.bind(on_release=self.button_up)
        self.var2.bind(on_press=self.button_down)
        self.var2.bind(on_release=self.play_var2)

        self.main = Button(
            text="- Main Menu",
            font_name="fonts/bradley.TTF",
            color=(0, 0, 0, 1),
            size=button_size,
            text_size=button_size,
            font_size=font_size,
            background_color=(0, 0, 0, 0),
        )
        self.main.bind(on_release=self.button_up)
        self.main.bind(on_press=self.button_down)
        self.main.bind(on_release=self.show_main)

        self.stop = Button(
            text="- Stop game",
            font_name="fonts/bradley.TTF",
            color=(0, 0, 0, 1),
            size=button_size,
            text_size=button_size,
            font_size=font_size,
            background_color=(0, 0, 0, 0),
        )
        self.stop.bind(on_release=self.button_up)
        self.stop.bind(on_press=self.button_down)
        self.stop.bind(on_release=self.stop_game)

        self.show_main()
        self.first = False

    def show_main(self, *kwagrs):
        self.remove_from_grid()
        if not self.first:
            self.parent.unload_settings()
        self.grid.add_widget(self.play)
        self.grid.add_widget(self.settings)

    def show_play(self, *kwargs):
        self.remove_from_grid()
        self.grid.add_widget(self.main)
        self.grid.add_widget(self.var1)
        self.grid.add_widget(self.var2)

    def show_settings(self, *kwargs):
        self.remove_from_grid()
        self.grid.add_widget(self.main)
        self.parent.load_settings()

    def play_var1(self, *kwargs):
        self.remove_from_grid()
        self.grid.add_widget(self.stop)
        self.parent.new_game(var=1)

    def play_var2(self, *kwargs):
        self.remove_from_grid()
        self.grid.add_widget(self.stop)
        self.parent.new_game(var=2)

    def remove_from_grid(self):
        self.grid.clear_widgets()

    def stop_game(self, *kwagrs):
        self.parent.stop_game()
        self.show_main()

    def button_down(self, *kwargs):
        kwargs[0].color = (0, 0, 0, 0.5)

    def button_up(self, *kwargs):
        kwargs[0].color = (0, 0, 0, 1)
Example #59
0
class DatePicker(BoxLayout):

    def __init__(self, *args, **kwargs):
        super(DatePicker, self).__init__(**kwargs)
        self.date = date.today()
        self.orientation = "vertical"
        self.month_names = ('January',
                            'February', 
                            'March', 
                            'April', 
                            'May', 
                            'June', 
                            'July', 
                            'August', 
                            'September', 
                            'October',
                            'November',
                            'December')
        if kwargs.has_key("month_names"):
            self.month_names = kwargs['month_names']
        self.header = BoxLayout(orientation = 'horizontal', 
                                size_hint = (1, 0.2))
        self.body = GridLayout(cols = 7)
        self.add_widget(self.header)
        self.add_widget(self.body)

        self.populate_body()
        self.populate_header()

    def populate_header(self, *args, **kwargs):
        self.header.clear_widgets()
        previous_month = Button(text = "<")
        previous_month.bind(on_press=partial(self.move_previous_month))
        next_month = Button(text = ">", on_press = self.move_next_month)
        next_month.bind(on_press=partial(self.move_next_month))
        month_year_text = self.month_names[self.date.month -1] + ' ' + str(self.date.year)
        current_month = Label(text=month_year_text, size_hint = (2, 1))

        self.header.add_widget(previous_month)
        self.header.add_widget(current_month)
        self.header.add_widget(next_month)

    def populate_body(self, *args, **kwargs):
        self.body.clear_widgets()
        date_cursor = date(self.date.year, self.date.month, 1)
        for filler in range(date_cursor.isoweekday()-1):
            self.body.add_widget(Label(text=""))
        while date_cursor.month == self.date.month:
            date_label = Button(text = str(date_cursor.day))
            date_label.bind(on_press=partial(self.set_date, 
                                                  day=date_cursor.day))
            if self.date.day == date_cursor.day:
                date_label.background_normal, date_label.background_down = date_label.background_down, date_label.background_normal
            self.body.add_widget(date_label)
            date_cursor += timedelta(days = 1)

    def set_date(self, *args, **kwargs):
        self.date = date(self.date.year, self.date.month, kwargs['day'])
        self.populate_body()
        self.populate_header()

    def move_next_month(self, *args, **kwargs):
        if self.date.month == 12:
            self.date = date(self.date.year + 1, 1, self.date.day)
        else:
            self.date = date(self.date.year, self.date.month + 1, self.date.day)
        self.populate_header()
        self.populate_body()

    def move_previous_month(self, *args, **kwargs):
        if self.date.month == 1:
            self.date = date(self.date.year - 1, 12, self.date.day)
        else:
            self.date = date(self.date.year, self.date.month -1, self.date.day)
        self.populate_header()
        self.populate_body()
class CalendarGenerator:
    now = datetime.datetime.now()
    month = now.month
    year = now.year
    day = now.day
    calendar_layout = ObjectProperty(None)
    month_button = ObjectProperty(None)
    year_button = ObjectProperty(None)

    def make_calendar(self):
        popup = Popup()
        popup.title = 'Calendar'
        layout = BoxLayout(orientation='vertical')
        inner_layout_1 = BoxLayout(size_hint=(1, 0.9),
                                   orientation='vertical')
        calendar_selection = GridLayout(cols=4,
                                        rows=1,
                                        size_hint=(1, 0.1))
        prev_month = Button(markup=True,
                            text="<",
                            font_size="30sp",
                            on_release=self.prev_month)
        next_month = Button(markup=True,
                            text=">",
                            font_size="30sp",
                            on_release=self.next_month)
        select_month = Factory.SelectMonth()
        self.month_button = Button(text='{}'.format(vars.month_by_number(self.month)),
                                   on_release=select_month.open)
        for index in range(12):
            month_options = Button(text='{}'.format(vars.month_by_number(index)),
                                   size_hint_y=None,
                                   height=40,
                                   on_release=partial(self.select_calendar_month, index))
            month_options.on_press = select_month.select(self.month_button.text)
            select_month.add_widget(month_options)

        select_month.on_select = lambda instance, x: setattr(self.month_button, 'text', x)
        select_year = Factory.SelectMonth()

        self.year_button = Button(text="{}".format(self.year),
                                  on_release=select_year.open)
        for index in range(10):
            year_options = Button(text='{}'.format(int(self.year) + index),
                                  size_hint_y=None,
                                  height=40,
                                  on_release=partial(self.select_calendar_year, index))
            year_options.on_press = select_year.select(self.year_button.text)

        select_month.bind(on_select=lambda instance, x: setattr(self.month_button, 'text', x))
        calendar_selection.add_widget(prev_month)
        calendar_selection.add_widget(self.month_button)
        calendar_selection.add_widget(self.year_button)
        calendar_selection.add_widget(next_month)
        self.calendar_layout = GridLayout(cols=7,
                                          rows=8,
                                          size_hint=(1, 0.9))
        self.create_calendar_table()

        inner_layout_1.add_widget(calendar_selection)
        inner_layout_1.add_widget(self.calendar_layout)
        inner_layout_2 = BoxLayout(size_hint=(1, 0.1),
                                   orientation='horizontal')
        inner_layout_2.add_widget(Button(markup=True,
                                         text="cancel",
                                         on_release=popup.dismiss))

        layout.add_widget(inner_layout_1)
        layout.add_widget(inner_layout_2)
        popup.content = layout
        popup.open()

    def create_calendar_table(self):
        self.calendar_layout.clear_widgets()
        calendars = Calendar()
        calendars.setfirstweekday(calendar.SUNDAY)
        selected_month = self.month - 1
        year_dates = calendars.yeardays2calendar(year=self.year, width=1)
        th1 = KV.invoice_tr(0, 'Su')
        th2 = KV.invoice_tr(0, 'Mo')
        th3 = KV.invoice_tr(0, 'Tu')
        th4 = KV.invoice_tr(0, 'We')
        th5 = KV.invoice_tr(0, 'Th')
        th6 = KV.invoice_tr(0, 'Fr')
        th7 = KV.invoice_tr(0, 'Sa')
        self.calendar_layout.add_widget(Builder.load_string(th1))
        self.calendar_layout.add_widget(Builder.load_string(th2))
        self.calendar_layout.add_widget(Builder.load_string(th3))
        self.calendar_layout.add_widget(Builder.load_string(th4))
        self.calendar_layout.add_widget(Builder.load_string(th5))
        self.calendar_layout.add_widget(Builder.load_string(th6))
        self.calendar_layout.add_widget(Builder.load_string(th7))
        if year_dates[selected_month]:
            for month in year_dates[selected_month]:
                for week in month:
                    for day in week:
                        if day[0] > 0:
                            item = Factory.CalendarButton(text="[b]{}[/b]".format(day[0]))
                        else:
                            item = Factory.CalendarButton(disabled=True)
                        self.calendar_layout.add_widget(item)

    def prev_month(self, *args, **kwargs):
        if self.month == 1:
            self.month = 12
            self.year -= 1
        else:
            self.month -= 1
        self.month_button.text = '{}'.format(vars.month_by_number(self.month))
        self.year_button.text = '{}'.format(self.year)
        self.create_calendar_table()

    def next_month(self, *args, **kwargs):
        if self.month == 12:
            self.month = 1
            self.year += 1
        else:
            self.month += 1
        self.month_button.text = '{}'.format(vars.month_by_number(self.month))
        self.year_button.text = '{}'.format(self.year)
        self.create_calendar_table()

    def select_calendar_month(self, month, *args, **kwargs):
        self.month = month
        self.make_calendar()

    def select_calendar_year(self, year, *args, **kwargs):
        self.year = year
        self.create_calendar_table()