Пример #1
0
def card(content, title=None, background_color=None, size=(.7, .5)):
    '''Вывод диалоговых окон с кастомным контентом.'''

    if not background_color:
        background_color = [1.0, 1.0, 1.0, 1]

    card = MDCard(size_hint=(1, 1), padding=5) #, background_color=background_color)

    if title:
        box = BoxLayout(orientation='vertical', padding=dp(8))
        box.add_widget(
            MDLabel(
                text=title, theme_text_color='Secondary', font_style="Title",
                size_hint_y=None, height=dp(36)
            )
        )
        box.add_widget(MDSeparator(height=dp(1)))
        box.add_widget(content)
        card.add_widget(box)
    else:
        card.add_widget(content)

    dialog = ModalView(size_hint=size, background_color=[0, 0, 0, .2])
    dialog.add_widget(card)
    #dialog.open()

    return dialog
Пример #2
0
    def helpView(self):
        """
        Show Help/Guides modal (show when help button pressed)
        """
        widgets = FloatLayout(size_hint=(None,None),
                         size=(300,300),
                         background_color=parse_color("#FF9933"),)
        sizer = NumericProperty(30)
        main = ModalView(title_color=parse_color("#FF9933"),
                     title_size=(25),
                     seperator_height=("9dp"),
                     separator_color=parse_color("#FF9933"),
                     #background_color=parse_color("#FF9933"),
                     size_hint=(None,None),
                     size=(400,620),
                     content = Image(source="coreEngine/Images/about.png"),
                             )
        

        
        white_bar = Image(source="coreEngine/Images/whitebar.png",
                          pos=(123,123),
                          size=(400,400))
        
        logo = Image(source="coreEngine/Images/about.png")
        
        main.add_widget(logo, 1)
        main.open()
Пример #3
0
    def save_new(self, *args):
        print("SAVE_NEW")
        print("path", path)
        # function to get text from text boxes
        servers = open(path +"\\" + 'server.json')
        try:
            ServerDict = json.load(servers)
        except ValueError:
            ServerDict = {}
        servers.close()

        grid = self.children[0]
        temp_list = [i.text for i in grid.children[4:0:-1]] # part of list becasue BoxLayout must be excluded
        # now need to check if all inputs have text

        nonBlock = True
        for item in temp_list:
            if len(item) < 1:
                nonBlock = False

        if nonBlock == True:
            if temp_list[0] in ServerDict.keys():
                p = ModalView(size_hint=(0.7, 0.1))
                p.add_widget(Label(text="Wybierz inna nazwe."))
                p.open()
            else: # here stuff will be saved
                ServerDict[temp_list[0]] = {"address":temp_list[1], "login":temp_list[2], "passw":temp_list[3]}
                servers = open(path+"\\"+'server.json', 'w')
                json.dump(ServerDict, servers)
                servers.close()
                self.dismiss()
        else:
            p = ModalView(size_hint=(0.7, 0.1))
            p.add_widget(Label(text="Błędne dane. Sprawdź i popraw..."))
            p.open()
Пример #4
0
    def Load(self):
        """
        Load from the Disk
        Button > Load()
        """
        from functools import partial
        from kivy.uix import filechooser
        from kivy.uix.filechooser import FileChooserListView, FileChooserIconView
        main = ModalView(size_hint=(.8,.8)) # everything on this Modal is 80%
        BL = BoxLayout(portrait="vertical")
        
        FLV = FileChooserListView(path="coreEngine/Saved",)
        
        

        def cTexloader(instance):
            Selected = FLV.selection
            Selected_Attr = Selected
            LStoString = str(Selected_Attr[0])
            self.Loader_NoErr(ctexSaved=LStoString,fixedPath=LStoString)
            
            
            


        

        Load_Btn = Button(text="Load this File")
        Load_Btn.bind(on_press=cTexloader)
        main.add_widget(BL)
        BL.add_widget(FLV) 
        BL.add_widget(Load_Btn)       

        main.open()
Пример #5
0
 def choose_color(self):
     view = ModalView()
     clrpr = ColorPicker()
     view.add_widget(clrpr)
     view.open()
     def on_color(instance, value):
         self.color_picked = value
     clrpr.bind(color=on_color)
Пример #6
0
def launchSimpleModal(text):
    view = ModalView(size_hint=(0.4, 0.2))
    content = SimpleModal(text=text)
    view.add_widget(content)
    # bind the on_press event of the button to the dismiss function
    content.bind(on_press=view.dismiss)
    # open the view
    view.open()
Пример #7
0
	def showGraph (self):
		if self.goals:
			show = ModalView (size_hint = (1, 1))
			close = Factory.ImageButton (size_hint = (1, 1))
			close.children[0].source = "graph/" + os.listdir ("graph")[self.current]
			close.children[0].size_hint = (1, 1)
			close.bind (on_press = show.dismiss)
			show.add_widget (close)
			show.open()
Пример #8
0
 def showLoading(self,txt="Loading ..."):
     cnt=BoxLayout()
     lbl=Label(text=txt)
     mdl=ModalView(size_hint=(0.9,0.3),auto_dismiss=False)
     cnt.add_widget(lbl)
     mdl.add_widget(cnt)
     mdl.open()
     self.loader=mdl
     self.setAnimation(self.loader)
Пример #9
0
 def on_touch_down(self, touch):
     if self.collide_point(touch.pos[0], touch.pos[1]):
         content = Rozpoziomowany()
         view = ModalView(size_hint=(None, None), size=(400, 400), auto_dismiss=False)
         view.add_widget(content)
         btn = content.ids['przejscie']
         btn2 = content.ids['menu']
         btn.bind(on_press=view.dismiss)
         btn2.bind(on_press=view.dismiss)
         view.open()
Пример #10
0
 def GameOverNote(self,survivaltime):
     popup = ModalView(size_hint=(0.75, 0.5))
     victory_label = Label(text="Game Over\n" + "%0.2f"%survivaltime + " sec", font_size=50)
     popup.add_widget(victory_label)
     popup.bind(on_dismiss=game.reset)
     popup.bind(on_press=popup.dismiss)
     popup.open()
Пример #11
0
 def set_language(self, language):
     language_map = {
         "English": "en_US",
         "简体中文": "zh_CN"
     }
     self.parent.configer.lang = language_map.get(language, "en_US")
     self.parent.configer.save_config()
     # show popup hint
     view = ModalView(size_hint=(None, None), size=(0, 0))
     view.add_widget(Label(text=_("This will take effect next time you start"), font_size=30))
     view.open()
Пример #12
0
    def on_pre_enter(self):
        for child in self.ids.grid.children:
                child.background_color = [1, 1, 1, 1]

        def my_callback(dt):
            view.dismiss()

        view = ModalView(size=(100, 100))
        view.background = 'img.jpg'
        view.open()
        Clock.schedule_once(my_callback, 5)
Пример #13
0
        def queryTableNames(n, callback):
            view = ModalView(size_hint=(None, None), size=(400, 200), background_color=(0, 0, 0, .6), auto_dismiss=True)

            def save_and_close(x):
                view.dismiss()
                callback(x)

            view.add_widget(QueryTableNamesWidget(n_tables=3, callback=save_and_close))
            view.open()
            print self.table_names
            return self.table_names
Пример #14
0
def modal_insert(self):
	lbl1 = Label(text='ID', id="lbl")
	lbl2 = Label(text='Nome', id="lbl")
	lbl3 = Label(text='Preco', id="lbl")
	lbl4 = Label(text='IVA', id="lbl")
	txt1 = TextInput(text='000', id="txtinp")
	txt2 = TextInput(text='Product Name', id="txtinp")
	txt3 = TextInput(text='123.45', id="txtinp")
	txt4 = TextInput(text='23', id="txtinp")

	insertion_grid = GridLayout(cols=2)
	insertion_grid.add_widget(lbl1)
	insertion_grid.add_widget(txt1)
	insertion_grid.add_widget(lbl2)
	insertion_grid.add_widget(txt2)
	insertion_grid.add_widget(lbl3)
	insertion_grid.add_widget(txt3)
	insertion_grid.add_widget(lbl4)
	insertion_grid.add_widget(txt4)
	# create content and assign to the view
	
	content = Button(text='Close me!')

	modal_layout = BoxLayout(orientation="vertical")
	modal_layout.add_widget(insertion_grid)

	def insert_def(self):
		input_list = []
		for text_inputs in reversed(self.parent.children[2].children):
			if text_inputs.id == "txtinp":
				input_list.append(text_inputs.text)
		print input_list
		grid.add_row(input_list, body_alignment, col_size, self)
		# print view
		# view.dismiss		


	insert_btn = Button(text="Insert", on_press=insert_def)	
	modal_layout.add_widget(insert_btn)
	modal_layout.add_widget(content)

	view = ModalView(auto_dismiss=False)

	view.add_widget(modal_layout)
	# bind the on_press event of the button to the dismiss function
	content.bind(on_press=view.dismiss)
	insert_btn.bind(on_release=view.dismiss)
	
	view.open()
Пример #15
0
 def on_back(self):
     # game still running, ask for user confirmation
     if self.state == 'running':
         SoundManager.play(Trigger.GAME_PAUSE)
         view = ModalView(size_hint=(None, None), size=(600, 400), auto_dismiss=False)
         content = Factory.STModalView(title='Spiel abbrechen', text='Das Spiel ist noch nicht beendet.\nWirklich abbrechen?', cb_yes=self.cancel_match, cb_no=self.resume_match)
         view.add_widget(content)
         view.open()
     # game not running anymore
     elif self.state in ['finished', 'submitting', 'submit_failed']:
         view = ModalView(size_hint=(None, None), size=(600, 400), auto_dismiss=False)
         content = Factory.STModalView(title='Spiel abbrechen', text='Das Ergebnis wurde noch nicht hochgeladen.\nWirklich abbrechen?', cb_yes=self.cancel_match)
         view.add_widget(content)
         view.open()
     else:
         self.manager.current = 'lounge'
Пример #16
0
  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()
Пример #17
0
 def __init__(self, **kwargs):
     ModalView.__init__(self, size_hint=(.15, 1), pos_hint={'right': 1},
                        **kwargs)
     app = App.get_running_app()
     scroller = ScrollView(do_scroll_x=False)
     layout = StackLayout(padding=[dp(10)], size_hint_y=None)
     layout.height = layout.width * len(app.powerups.purchased)
     for powerup in app.powerups.purchased:
         if not isinstance(powerup, Powerup):
             continue
         if powerup.type == PowerupType.PLAY_CARD:
             if not app.loaded_deck.get_cards(app.powerups.cards()):
                 continue
         layout.add_widget(UsablePowerupIcon(powerup=powerup,
                                             size_hint=(1, None)))
     scroller.add_widget(layout)
     self.add_widget(scroller)
Пример #18
0
 def on_press_bt_selected_two_equal_periods(self):
     popup = ModalView(size_hint=(None,None))
     popup.add_widget(Label(text=lang['Selected_two_equal_periods'],size_hint=(None,None),height=30, width=300))
     popup.height = 40
     popup.width = 300
     popup.open()
     print('selected two equal periods')
Пример #19
0
    def on_status(self, instance, new_value):
        status = new_value

        # Sum each row, column and diagonal.
        # Could be shorter, but let's be extra
        # clear what’s going on

        sums = [sum(status[0:3]), # rows
               sum(status[3:6]), sum(status[6:9]), sum(status[0::3]), # columns
               sum(status[1::3]), sum(status[2::3]), sum(status[::4]), # diagonals
               sum(status[2:-2:2])]

        # Sums can only be +-3 if one player
        # filled the whole line
        winner = None

        if -3 in sums:
            winner = 'Крестик Выиграл!'
        elif 3 in sums:
            winner = 'Нолик Выиграл!'
        elif 0 not in self.status:
            winner = 'Ничья....!'

        if winner:
            popup = ModalView(size_hint=(0.75, 0.5))
            victory_label = Label(text=winner, font_size=50)
            popup.add_widget(victory_label)
            popup.bind(on_dismiss=self.reset)
            popup.open()
Пример #20
0
    def button_pressed(self, button):
        player = {1: 'X', -1: 'O'}
        colours = {1: (0, 1, 0, 1), -1: (1, 0, 0, 1)}

        x, y, z, w = button.coords
        already_played = self.board[x, y, z, w] != 0

        if not already_played:
            self.board[x, y, z, w] = self.current_player
            button.text = player[self.current_player]
            button.background_color = colours[self.current_player]
            winner = None
            if check_win(move = button.coords, player = self.current_player, \
                        moves = self.move_list[self.current_player], \
                        board = self.board):
                winner = '{0} wins!'.format(player[self.current_player])
            elif 0 not in self.board:
                winner = 'Draw... nobody wins!'
            if winner:
                popup = ModalView(size_hint=(0.75, 0.5))
                victory_label = Label(text=winner, font_size=50)
                popup.add_widget(victory_label)
                popup.bind(on_dismiss=self.reset)
                popup.open()
            else:
                self.current_player *= -1
Пример #21
0
	def on_status(self, instance, new_value):
		status = new_value

		# Sum each row, col and diag
		# Could be shorter, but let's be extra
		# clear what's going on

		sums = [#rows
				sum(status[0:3]),
				#columns
				sum(status[3:6]),
				sum(status[6:9]),
				sum(status[0::3]),
				#diagonals
				sum(status[1::3]), 
				sum(status[2::3]),
				sum(status[::4]),
				sum(status[2:-2:2])]
		# Sums can only be +-3 if one player
		# filled the whole line

		winner = ''
		if 3 in sums:
			winner = '{} win!'.format('O')
		elif -3 in sums:
			winner = '{} win!'.format('X')
		elif 0 not in self.status: #Grid full
			winner = 'Draw...Nobody wins!'

		if winner:
			popup = ModalView(size_hint = (0.75 , 0.5 ))
			victory_label = Label(text = winner, font_size = 50)
			popup.add_widget(victory_label)
			popup.bind(on_dismiss = self.reset)
			popup.open()
Пример #22
0
    def show_modal(self, dt):
        modal = ModalView(size_hint=(0.5, 0.3), auto_dismiss=False)
        modalBox = BoxLayout(orientation="vertical", spacing=5, padding=10)
        txt = TextInput(hint_text="Takma ad giriniz...", size_hint=(1, None), height=50)
        modalBox.add_widget(txt)
        modalBtn = Button(text="Tamam", size_hint=(1, None), height=50)

        def setNick(instance):
            self.setted = True
            self.nick = txt.text
            modal.dismiss()
            self.root.opacity = 1
            self.connect_to_server()

        modalBtn.bind(on_release=setNick)
        modalBox.add_widget(modalBtn)
        modal.add_widget(modalBox)
        modal.open()
Пример #23
0
    def on_preferences(self, *args):
        settings_view = SettingsWithNoMenu()
        base_dir = self._settings.base_dir
        settings_view.add_json_panel('Dashboard Preferences', self._settings.userPrefs.config, os.path.join(base_dir, 'resource', 'settings', 'dashboard_settings.json'))

        popup = ModalView(size_hint=DashboardView._POPUP_SIZE_HINT)
        popup.add_widget(settings_view)
        popup.bind(on_dismiss=self._popup_dismissed)
        popup.open()
        self._popup = popup
Пример #24
0
class ButtonTreeItem(Button):
  def __init__(self, num, outward, **kwargs):
    super(ButtonTreeItem, self).__init__(**kwargs)
    self.size = (20, window_height/btnHeightRate) # 20 isn't change anything
    self.size_hint_y = None
    self.num = num
    self.context = False
    self.outward = outward

  def on_touch_down(self, touch):
    if self.collide_point(*touch.pos):
      self.create_clock()
    return super(ButtonTreeItem, self).on_touch_down(touch) 
  def on_touch_up(self, touch):
    if self.collide_point(*touch.pos):
      self.delete_clock()
      if self.context :
        self.context = False
        return True 
    return super(ButtonTreeItem, self).on_touch_up(touch) 

  def create_clock(self, *args):
    Clock.schedule_once(self.openContextMenu, timeOut_forContextMenu)
  def delete_clock(self, *args):
    Clock.unschedule(self.openContextMenu)

  def openContextMenu(self, *args):
    self.context = True
    self.contextMenu = ModalView(size_hint=(0.5, 0.5))
    self.contextMenu.bind(on_dismiss=self.outward.showTree())
    contextLayout = BoxLayout(
        padding = 10,
        spacing = 10,
        pos_hint = {'center_x': 0.5, 'center_y': 0.5}, 
        size_hint = (0.7, 0.8), 
        orientation = 'vertical')
    contextLayout.add_widget(Label(text=self.text))
    btnDelete = Button(text='delete')
    btnDelete.bind(on_press=self.delete)
    contextLayout.add_widget(btnDelete)
    close = Button(text='close')
    close.bind(on_release=self.contextMenu.dismiss)
    contextLayout.add_widget(close)
    self.contextMenu.add_widget(contextLayout)
    self.contextMenu.open()
  def delete(self, *args):
    tree.curItem().remove(self.num)
    self.contextMenu.dismiss()
    self.outward.showTree()
Пример #25
0
    def countDown(self,dt):
        self.total -=dt
        if self.total<=0:
            Clock.unschedule(self.countDown)
            if self.game.root.get_current=="end_screen":
                self.game.root.current="main_screen"
            tmo=SoundLoader.load("sounds/time_over.ogg")
            tmo.volume=self.vol
            tmo.play()
            cnt=BoxLayout(orientation="vertical",size_hint=(.9,0.7),pos_hint={"center_x":0.5,"center_y":0.5})
            modal=ModalView(size_hint=(0.5,0.5),auto_dismiss=False,pos_hint={"center_x":0.5,"center_y":0.5})
            lbl=Label(text="[color=#aef4f3]Time Out![/color]",markup=True,size_hint=(1,None),height=30)
            btnplay=Button(text="Replay",size_hint=(1,None),height=50)
            btnquit=Button(text="Quit",size_hint=(1,None),height=50)
            def replay(inst):
                if modal:
                    modal.dismiss()
                    self.newGame()
            def quit(inst):
                if modal:
                    modal.dismiss()
                    self.game.go("exit")


            btnplay.bind(on_release=replay)
            btnquit.bind(on_release=quit)
            cnt.add_widget(lbl)
            cnt.add_widget(btnplay)
            cnt.add_widget(btnquit)
            modal.add_widget(cnt)
            modal.open()
            return
        min,sec=divmod(self.total,60)
        min=int(min)
        sec=int(sec)
        self.game.timer=str(min)+":"+str(sec)
Пример #26
0
    def posted(self,inst,data):
        import json
        from time import strptime,strftime,time
        res=json.loads(data.decode()) if not isinstance(data,dict) else data
        scores=res["scores"]
        modal=ModalView(size_hint=(0.8,0.65))
        scrl=ScrollView(size_hint=(0.9,0.9),spacing=2)
        cnt=BoxLayout(orientation="vertical",size_hint=(1,None),height=50)
        mb=BoxLayout()
        lbl=Label(text="[color=#aef4f3]Name[/color]",markup=True)
        mb.add_widget(lbl)
        lbl=Label(text="[color=#aef4f3]Score[/color] ",markup=True)
        mb.add_widget(lbl)
        lbl=Label(text="[color=#aef4f3]Date[/color] ",markup=True)
        mb.add_widget(lbl)
        cnt.add_widget(mb)
        for score in scores:
            bx=BoxLayout()
            with bx.canvas.before:
                Color(get_color_from_hex("#abc"))

            lbl=Label(text=score["ad"])
            bx.add_widget(lbl)
            lbl=Label(text=score["puan"])
            bx.add_widget(lbl)
            tms=strptime(score["zaman"],"%Y-%m-%d %H:%M:%S")
            lbl=Label(text=str(tms.tm_mday)+"."+str(tms.tm_mon)+"."+str(tms.tm_year))
            bx.add_widget(lbl)
            cnt.add_widget(bx)
        cnt.height=len(scores)*50
        scrl.add_widget(cnt)
        modal.add_widget(scrl)
        if self.loader:
            self.loader.dismiss()
        modal.open()
        self.setAnimation(modal,once=True)
Пример #27
0
 def pokazDodanieObiektu(self, *args):
     view = ModalView(size_hint=(None, None), size=(640, 480))
     box = BoxLayout(orientation="vertical",spacing=10)
     scrollView = ScrollView(bar_margin=10, bar_color=[1,1,1,1])
     viewWrapper = GridLayout(cols=2, row_default_height=40,size_hint_y=None,padding=[-20,20,20,20])
     viewWrapper.bind(minimum_height=viewWrapper.setter('height'))
     
     listaTextBoxow = []
     
     for i in range(len(self.sharedInstance.data.temp)):
         l = Label(text=self.sharedInstance.data.temp[i],halign="left", width=50)
         #textPlaceHolder = 'Tutaj wpisz wartosc dla {0}'.format(self.sharedInstance.data.temp[i])
         #textPlaceHolder,multiline=False,  )
         textinput = TextInput(multiline=False, text="0",focus=True) 
         listaTextBoxow.append(textinput)
         viewWrapper.add_widget(l)
         viewWrapper.add_widget(textinput)
         #background_color=[51/255.0, 181.0/255, 229/255.0,1]
     scrollView.add_widget(viewWrapper)
     box.add_widget(scrollView)
     box.add_widget(Button(text='Dodaj', font_size=14, on_press=partial(self.dodajObiekt,view, listaTextBoxow), size_hint=(1, .1)))
     view.add_widget(box)
     view.open()
     return view
Пример #28
0
    def _start_stopwatch(self):
        '''
        Starts the stopwatch timer
        '''

        if not self._popup:
            self._popup = ModalView(size_hint=self._POPUP_SIZE_HINT, auto_dismiss=False)
            self._popup.add_widget(self)
        self._set_exit_speed_frame_visible(False)
        self._popup.open()
        self._current_time = 0.0
        self._start_time = time()
        self._flash_count = 0
        self._currently_racing = False
        Clock.schedule_interval(self._tick_stopwatch, self._STOPWATCH_TICK)
Пример #29
0
 def exit(self):
     self.popup = ModalView(size_hint=(0.5, 0.4))
     grd = GridLayout()
     grd.cols = 2
     grd.padding = 120
     flt = FloatLayout()
     lbl = Label(pos=(320, 340), text='Are you sure to exit game????', font_size=35)
     flt.add_widget(lbl)
     btn1 = Button(text='YES', font_size=50)
     btn1.bind(on_press=self.button_pressed)
     btn2 = Button(text='NO', font_size=50)
     btn2.bind(on_press=self.popup.dismiss)
     grd.add_widget(btn1)
     grd.add_widget(btn2)
     self.popup.add_widget(flt)
     self.popup.add_widget(grd)
     self.popup.open()
Пример #30
0
    def on_preferences(self, *args):
        """
        Display the dashboard preferences view 
        """
        settings_view = DashboardPreferences(self._settings, self._dashboard_factory)

        def popup_dismissed(*args):
            self._notify_preference_listeners()
            screens = settings_view.get_selected_screens()
            screens = self._filter_dashboard_screens(screens)
            self._settings.userPrefs.set_dashboard_screens(screens)
            self._update_screens(screens)

        popup = ModalView(size_hint=DashboardView._POPUP_SIZE_HINT)
        popup.add_widget(settings_view)
        popup.bind(on_dismiss=popup_dismissed)
        popup.open()
Пример #31
0
    def get_time(self):
        mv = ModalView(size_hint=[.8, .6])
        box = BoxLayout(orientation='vertical', size_hint=[.5, .5])
        mv.add_widget(box)

        cl = CTP(color=[1, 1, 1, 1])
        cl.bind(time=self.set_time)

        submit = Button(text='OK',
                        background_normal='',
                        background_color=rgba('#ffffff'),
                        color=rgba('#0e1574ff'),
                        size_hint_y=.2)

        submit.bind(on_release=lambda x: self.update_time(cl.time, mv))
        box.add_widget(cl)
        box.add_widget(submit)
        mv.open()
Пример #32
0
    def age_index(self):
        pop1 = ModalView(size_hint=(.6, .3), auto_dismiss=True)
        rount = GridLayout(cols=1, rows=7)
        ester = Button(text='AGEING INDEX', background_color=(0, 0, .9, .5))
        po1 = TextInput(hint_text='A', input_filter='int', write_tab=False)
        po2 = TextInput(hint_text='Area in Km2',
                        input_filter='int',
                        write_tab=False)
        po3 = TextInput(hint_text='Area in Km2',
                        input_filter='int',
                        write_tab=False)
        result = Label(text='text')

        def cal_young_dend_ratio(self):
            if po1.text != '' and po2.text != '':
                pe1 = int(po1.text)
                p3 = int(po2.text)
                r = round((pe1 / p3) * 100, 0)
                result.text = str(r)
            else:
                d = Popup(title='Wrong Input',
                          size_hint=(.5, .5),
                          auto_dismiss=True)
                b = Button(text='textinputs cannot be empty',
                           on_press=d.dismiss)
                d.add_widget(b)
                d.open()

        b = BoxLayout()
        cal_proj = Button(text='CALCULATE AGEING INDEX')
        backhome = Button(text='back home', on_press=pop1.dismiss)
        b.add_widget(cal_proj)
        b.add_widget(backhome)

        rount.add_widget(ester)
        rount.add_widget(po1)
        rount.add_widget(po2)
        rount.add_widget(po3)
        rount.add_widget(result)
        rount.add_widget(b)
        pop1.add_widget(rount)

        pop1.open()
        cal_proj.bind(on_press=cal_young_dend_ratio)
Пример #33
0
    def yong_dend_ratio(self):
        pop1 = ModalView(size_hint=(.9, .5), auto_dismiss=True)
        rount = GridLayout(cols=1, rows=7)
        ester = Button(text='YOUNG DEPENDENCY RATIO',
                       background_color=(0, 0, .9, .5))
        po1 = TextInput(hint_text='Children under Age 15',
                        input_filter='int',
                        write_tab=False)
        po2 = TextInput(hint_text='Adults between ade 15 and 64',
                        input_filter='int',
                        write_tab=False)

        result = Label(text='text')

        def cal_young_dend_ratio(self):
            if po1.text != '' and po2.text != '':
                pe1 = int(po1.text)
                p3 = int(po2.text)
                r = round((pe1 / p3) * 100, 0)
                result.text = str(r)
            else:
                d = Popup(title='Wrong Input',
                          size_hint=(.5, .3),
                          auto_dismiss=True)
                b = Button(text='textinputs cannot be empty',
                           on_press=d.dismiss)
                d.add_widget(b)
                d.open()

        b = BoxLayout()
        cal_proj = Button(text='CALCULATE  YOUNG DENPENDENCY RATIO')
        backhome = Button(text='back home', on_press=pop1.dismiss)
        b.add_widget(cal_proj)
        b.add_widget(backhome)

        rount.add_widget(ester)
        rount.add_widget(po1)
        rount.add_widget(po2)
        rount.add_widget(result)
        rount.add_widget(b)
        pop1.add_widget(rount)

        pop1.open()
        cal_proj.bind(on_press=cal_young_dend_ratio)
Пример #34
0
    def reset(self, yes=0):
        if App.get_running_app().man.if_online == 0 or yes == 1:
            App.get_running_app().waiting_for_answer = 0
            try:
                self.want_reset.dismiss()
            except:
                pass
            self.parent.parent.ids.gra.status = [0] * 9
            BigBoard.current_player = -1
            BigBoard.status = [0] * 9
            try:
                App.get_running_app().clock_timer.cancel()
            except:
                pass
            BigBoard.MinTime = "00"
            self.parent.parent.ids.pasek.timeInGame = "00 : 00"
            BigBoard.where = -1
            BigBoard.are_we_playing = True
            for child in self.parent.parent.ids.gra.children:
                child.status = [0] * 9
                child.still_playing = 1
                child.background_image = ''
                for button in child.children:
                    button.background_normal = ""
                    button.background_color = (.32, .32, .32, 1)
                child.r = .5
                child.g = .5
                child.b = .5

        elif App.get_running_app().man.if_online == 1:
            self.want_reset = ModalView(size_hint=(.75, .5))
            reset_text = Label(text="waiting for opponent", font_size=50)
            App.get_running_app().waiting_for_answer = 1
            self.want_reset.add_widget(reset_text)
            App.get_running_app().s.reset()
            self.want_reset.open()
Пример #35
0
    def popden(self):
        pop1 = ModalView(size_hint=(.7, .5), auto_dismiss=True)
        rount = GridLayout(cols=1, rows=7)
        ester = Button(text='POPULATION DENSITY',
                       background_color=(0, 0, .9, .5))
        po1 = TextInput(hint_text='population at initial date',
                        input_filter='int',
                        write_tab=False)
        po2 = TextInput(hint_text='Area in Km2',
                        input_filter='int',
                        write_tab=False)
        result = Label()

        def cal_pop_den(self):
            if po1.text != '' and po2.text != '':
                pe1 = int(po1.text)
                p3 = int(po2.text)
                r = round((pe1 / p3), 0)
                result.text = str(r)
            else:
                d = Popup(title='Wrong Input',
                          size_hint=(.5, .5),
                          auto_dismiss=True)
                b = Button(text='textinputs cannot be empty',
                           on_press=d.dismiss)
                d.add_widget(b)
                d.open()

        b = BoxLayout()
        cal_proj = Button(text='CALCULATE POPULATON DENSITY')
        backhome = Button(text='back home', on_press=pop1.dismiss)
        b.add_widget(cal_proj)
        b.add_widget(backhome)

        rount.add_widget(ester)
        rount.add_widget(po1)
        rount.add_widget(po2)
        rount.add_widget(result)
        rount.add_widget(b)
        pop1.add_widget(rount)

        pop1.open()
        cal_proj.bind(on_press=cal_pop_den)
Пример #36
0
    def announce_winner(self, winner):
        if winner == 1:
            winner = 'Winner X'
        elif winner == -1:
            winner = 'Winner O'
        elif winner == 0:
            winner = 'Draw'
        popup = ModalView(size_hint=(None, None), size=(400, 200))
        victory_label = Button(text=winner,
                               font_size=50,
                               background_color=[0, 1, 0, 1])
        popup.add_widget(victory_label)
        popup.open()
        self.reset_game()

        if not (os.path.isfile('winner_count.pkl')):
            winner_count = dict()
            winner_count['Winner O'] = 0
            winner_count['Winner X'] = 0
            winner_count['Draw'] = 0

            print winner_count
            winner_count[str(winner)] = 1
            print winner_count

            with open('winner_count.pkl', 'w') as f:
                pickle.dump(winner_count, f)
                print 'Saved a new winner_count'

        else:
            with open('winner_count.pkl') as f:
                winner_count = pickle.load(f)
                print 'Loaded the winner_count'

            print winner
            print winner_count
            winner_count[winner] = winner_count[winner] + 1

            with open('winner_count.pkl', 'w') as f:
                pickle.dump(winner_count, f)
                print 'Saved a new winner_count'

            print winner_count
Пример #37
0
    def on_status(self, coords, who_win):
        BigBoard.status[coords] = who_win

        win = function.if_sb_win(BigBoard.status)
        winner = ''
        if win == 1:
            winner = "X win!"
        elif win == -1:
            winner = "O win!"
        elif win == 6:
            winner = "Draw!"

        if winner:
            popup = ModalView(size_hint=(0.75, 0.5))
            victory_label = Label(text=winner, font_size=50)
            popup.add_widget(victory_label)
            self.clockTimer = False
            popup.open()
            self.parent.parent.parent.ids.pasek.reset(1)
            BigBoard.are_we_playing = False
Пример #38
0
 def solve_board(self):
     '''Provides sudoku board data for the solve() function'''
     global cellArray, board
     inputBoard = []
     for row in range(BOARD_SIZE):
         inputBoard.append([
             int(elem.text) if elem.text else 0
             for elem in cellArray[row * BOARD_SIZE:(row + 1) * BOARD_SIZE]
         ])
     if check_board_validity(inputBoard, BOARD_SIZE) == "Valid":
         board = inputBoard.copy()
         solve(self)
         for row in range(BOARD_SIZE):
             for col in range(BOARD_SIZE):
                 cellArray[row * BOARD_SIZE + col].text = str(
                     board[row][col]) if board[row][col] else ""
     else:
         solve_modal_view = ModalView()
         solve_modal_view.add_widget(Label(text="Invalid Board"))
         solve_modal_view.open()
Пример #39
0
    def promptDialog(self, state):
        modal = ModalView(title="Continue?", size_hint=(0.5, 0.3))
        label = Label(
            text="Currently waiting for Data. Do you want to disconnect?",
            size_hint=(1, .7))
        btn_ok = Button(text="Yes",
                        on_press=self.promptDialogYes,
                        on_release=modal.dismiss)
        btn_no = Button(text="No", on_release=modal.dismiss)

        outerbox = BoxLayout(orientation='vertical')
        box = BoxLayout(spacing=10,
                        size_hint=(1, .3),
                        padding=[10, 10, 10, 10])
        box.add_widget(btn_ok)
        box.add_widget(btn_no)
        outerbox.add_widget(label)
        outerbox.add_widget(box)

        modal.add_widget(outerbox)
        modal.open()
Пример #40
0
 def show_filemanager_add_help_location(self):
     """
     Show a dialog to ask the name of the new help.
     :return:
     """
     mode = False
     modal_view = ModalView(size_hint=(1, 1), auto_dismiss=False)
     file_manager = MDFileManager(
         exit_manager=lambda *args: self.on_cancel_filemanager(
             modal_view, *args),
         select_path=lambda *args: self.on_selected_path_filemanager(
             modal_view, *args),
         previous=
         mode  # Very special naming convention, False means listview-mode, True means Thumbnail mode
     )
     modal_view.add_widget(file_manager)
     file_manager.show(
         str(
             pl.Path(CU.tfs.dic['tf_workspace_path'].value /
                     CU.tfs.dic['RAW_MIDI_DIR_NAME'].value)))
     modal_view.open()
Пример #41
0
    def _remove_book(self, book=None, func=None):
        modal_spinner = ModalView(size_hint=(None, None),
                                  size=(100, 100),
                                  auto_dismiss=False,
                                  background='',
                                  background_color=(1, 1, 1, 0))
        modal_spinner.add_widget(MDSpinner(size_hint=(0.7, 0.7), active=True))
        self.modal_spinner = modal_spinner

        modal_spinner.open()

        def thread_func():
            book.epub_remove()
            clear_func()

        @mainthread
        def clear_func():
            func()
            modal_spinner.dismiss()

        Thread(target=thread_func).start()
Пример #42
0
class Example(App):
    theme_cls = ThemeManager()
    theme_cls.primary_palette = 'Teal'
    title = "File Manage"
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        Window.bind(on_keyboard=self.events)
        self.manager_open = False
        self.manager = None
    def build(self):
        return Factory.ExampleFileManager()
    def file_manager_open(self):
        if not self.manager:
            self.manager = ModalView(size_hint=(1, 1), auto_dismiss=False)
            self.file_manager = MDFileManager(
                exit_manager=self.exit_manager, select_path=self.select_path)
            self.manager.add_widget(self.file_manager)
            self.file_manager.show('/')  # output manager to the screen
        self.manager_open = True
        self.manager.open()
    def select_path(self, path):
        '''It will be called when you click on the file name
        or the catalog selection button.
        :type path: str;
        :param path: path to the selected directory or file;
        '''
        self.exit_manager()
        toast(path)
    def exit_manager(self, *args):
        '''Called when the user reaches the root of the directory tree.'''
        self.manager.dismiss()
        self.manager_open = False
    def events(self, instance, keyboard, keycode, text, modifiers):
        '''Called when buttons are pressed on the mobile device..'''
        if keyboard in (1001, 27):
            if self.manager_open:
                self.file_manager.back()
        return True
Пример #43
0
    def popUpNuevoUsuario(self):
        view = ModalView(size_hint=(None, None), size=(400, 400))
        layout = BoxLayout(orientation='vertical')
        tinput1 = TextInput(text="", hint_text="Nombre")
        tinput2 = TextInput(text="", hint_text="Password", password=True)
        label1 = Label(text="Nombre de Usuario:")
        label2 = Label(text="Contraseña:")
        spinner1 = Spinner(text="Administrador",
                           values=("Administrador", "Usuario con privilegios",
                                   "Usuario comun"))
        layout.add_widget(label1)
        layout.add_widget(tinput1)
        layout.add_widget(label2)
        layout.add_widget(tinput2)
        layout.add_widget(spinner1)
        btn1 = Button(
            text="Agregar nuevo usuario",
            on_press=lambda a: dbRef.agregarUsuario(
                tinput1.text, tinput2.text, spinner1.text, usuarioActual[1]))
        layout.add_widget(btn1)
        view.add_widget(layout)

        view.open()
Пример #44
0
def card_with_buttons(content,
                      title=None,
                      background_color=None,
                      size=(.7, .5),
                      buttons=None):
    '''Вывод диалоговых окон с кастомным контентом.'''

    if not background_color:
        background_color = [1.0, 1.0, 1.0, 1]

    card = MDDialog(size_hint=(1, 1),
                    padding=5,
                    background_color=background_color)

    if title:
        box = BoxLayout(orientation='vertical', padding=dp(8))
        box.add_widget(
            MDLabel(text=title,
                    theme_text_color='Secondary',
                    font_style="Title",
                    size_hint_y=None,
                    height=dp(36)))
        box.add_widget(MDSeparator(height=dp(1)))
        box.add_widget(content)
        card.add_widget(box)
    else:
        card.add_widget(content)

    for list_button in buttons:
        text_button, action_button = list_button
        card.add_action_button(text_button, action=action_button)

    dialog = ModalView(size_hint=size, background_color=[0, 0, 0, .2])
    dialog.add_widget(card)
    dialog.open()

    return dialog
Пример #45
0
    def _get_books(self):
        search_box = self.ids.search_box
        books_list = self.ids.books_list

        terms = search_box.ids.input.text.strip()
        if not terms:
            search_box.ids.input.text = ''
            return

        modal_spinner = ModalView(size_hint=(None, None),
                                  size=(100, 100),
                                  auto_dismiss=False,
                                  background='',
                                  background_color=(1, 1, 1, 0))
        modal_spinner.add_widget(MDSpinner(size_hint=(0.7, 0.7), active=True))
        self.modal_spinner = modal_spinner

        def thread_func():
            books = search_books(terms)
            self._update_books(books)

        modal_spinner.open()

        Thread(target=thread_func).start()
Пример #46
0
    def load_kv(self):

        m = ModalView(size_hint=[.6, .7])
        box = BoxLayout(orientation='vertical')
        m.add_widget(box)

        name_box = BoxLayout(size_hint_y=.1)

        fc = OpenFChooser()
        box.add_widget(name_box)
        box.add_widget(fc)
        submit = Button(text='open',
                        background_color=[1, 1, 1, 1],
                        background_normal='',
                        color=[0, 0, 0, 1],
                        size_hint_x=.2)
        submit.bind(on_press=lambda x: self.update_name_open_file(
            fc.get_selected_file(), m))
        # submit.bind(on_press= lambda x: self.show_kv(None,'New UI'))
        name_box.add_widget(submit)

        # print(fc.get_selected_file())

        m.open()
Пример #47
0
 def generate(self, difficulty):
     for row in range(9):
         for col in range(9):
             if self.text_inputs[9 * row + col] != 0:
                 self.text_inputs[9 * row + col].text = ""
                 self.text_inputs[9 * row + col].readonly = False
                 self.text_inputs[
                     9 * row + col].background_color = 0.23, 0.23, 0.23, 1
     hint = ModalView(size_hint=(None, None), size=(400, 200))
     hint.add_widget(
         Label(text='To check if number is corrent,' + '\n' +
               'select it and press enter',
               font_size=20))
     hint.open()
     board = generate.generate(5 - difficulty)
     while type(board) == bool:
         board = generate.generate(5 - difficulty)
     for row in range(9):
         for col in range(9):
             if board[row][col] != 0:
                 self.text_inputs[9 * row + col].text = str(board[row][col])
                 self.text_inputs[9 * row + col].readonly = True
                 self.text_inputs[
                     9 * row + col].background_color = 0.43, 0.43, 0.43, 1
Пример #48
0
    def write_rcp_config(self, info_msg, callback):
        def timeout(dt):
            progress_view.dismiss()
            Clock.schedule_once(lambda dt: callback(), 0.25)

        def write_win(details):
            msg.text += ' Success'
            self.rc_config.stale = False
            Clock.schedule_once(timeout, 1.5)

        def write_fail(details):
            progress_view.dismiss()
            okPopup(
                'Oops!',
                'We had a problem updating the device. Check the device connection and try again.\n\nError:\n\n{}'
                .format(details), lambda *args: None)

        progress_view = ModalView(size_hint=(None, None),
                                  size=(dp(600), dp(200)))
        msg = FieldLabel(text=info_msg, halign='center')
        progress_view.add_widget(msg)
        progress_view.open()

        self.rc_api.writeRcpCfg(self.rc_config, write_win, write_fail)
Пример #49
0
    def show(self, path):
        """Forms the body of a directory tree.

        :param path: The path to the directory that will be opened in the file manager.
        """

        dirs, files = self.get_content(path)

        if self.previous:
            threading.Thread(target=self._create_previous, args=(path,)).start()
            split_dirs = self._split_list(dirs, 3)
            split_files = self._split_list(files, 3)

        self.current_path = path
        manager_list = []

        if dirs == [] and files == []:  # selected directory
            pass
        elif not dirs and not files:  # directory is unavailable
            return

        if self.previous:
            for list_dirs in split_dirs:
                manager_list.append(
                    {
                        "viewclass": "BodyManagerWithPrevious",
                        "path": path,
                        "icon_folder": self.icon_folder,
                        "paths": list_dirs,
                        "type": "folder",
                        "events_callback": self.select_dir_or_file,
                        "height": dp(105),
                    }
                )
            for list_files in list(split_files):
                manager_list.append(
                    {
                        "viewclass": "BodyManagerWithPrevious",
                        "path": path,
                        "icon_folder": self.icon_folder,
                        "paths": list_files,
                        "type": "files",
                        "events_callback": self.select_dir_or_file,
                        "height": dp(105),
                    }
                )
        else:
            for name in dirs:
                _path = path + name if path == "/" else path + "/" + name
                access_string = self.get_access_string(_path)
                if "r" not in access_string:
                    icon = "folder-lock"
                else:
                    icon = "folder"

                manager_list.append(
                    {
                        "viewclass": "BodyManager",
                        "path": _path,
                        "icon": icon,
                        "dir_or_file_name": name,
                        "events_callback": self.select_dir_or_file,
                    }
                )
            for name in files:
                _path = path + name if path == "/" else path + "/" + name
                manager_list.append(
                    {
                        "viewclass": "BodyManager",
                        "path": _path,
                        "icon": "file-outline",
                        "dir_or_file_name": name,
                        "events_callback": self.select_dir_or_file,
                    }
                )
        self.ids.rv.data = manager_list

        if not self._window_manager:
            self._window_manager = ModalView(
                size_hint=(1, 1), auto_dismiss=False
            )
            self._window_manager.add_widget(self)
        if not self._window_manager_open:
            self._window_manager.open()
            self._window_manager_open = True
Пример #50
0
class MDFileManager(ThemableBehavior, MDFloatLayout):
    icon = StringProperty("check")
    """
    The icon that will be used on the directory selection button.

    :attr:`icon` is an :class:`~kivy.properties.StringProperty`
    and defaults to `check`.
    """

    icon_folder = StringProperty(f"{images_path}folder.png")
    """
    The icon that will be used for folder icons when using ``previous = True``.

    :attr:`icon` is an :class:`~kivy.properties.StringProperty`
    and defaults to `check`.
    """

    exit_manager = ObjectProperty(lambda x: None)
    """
    Function called when the user reaches directory tree root.

    :attr:`exit_manager` is an :class:`~kivy.properties.ObjectProperty`
    and defaults to `lambda x: None`.
    """

    select_path = ObjectProperty(lambda x: None)
    """
    Function, called when selecting a file/directory.

    :attr:`select_path` is an :class:`~kivy.properties.ObjectProperty`
    and defaults to `lambda x: None`.
    """

    ext = ListProperty()
    """
    List of file extensions to be displayed
    in the manager. For example, `['py', 'kv']` - will filter out all files,
    except python scripts and Kv Language.

    :attr:`ext` is an :class:`~kivy.properties.ListProperty`
    and defaults to `[]`.
    """

    search = OptionProperty("all", options=["all", "files"])
    """
    It can take the values 'dirs' 'files' - display only directories
    or only files. By default, it displays and folders, and files.
    Available options are: `'all'`, `'files'`.

    :attr:`search` is an :class:`~kivy.properties.OptionProperty`
    and defaults to `all`.
    """

    current_path = StringProperty(os.getcwd())
    """
    Current directory.

    :attr:`current_path` is an :class:`~kivy.properties.StringProperty`
    and defaults to `/`.
    """

    use_access = BooleanProperty(True)
    """
    Show access to files and directories.

    :attr:`use_access` is an :class:`~kivy.properties.BooleanProperty`
    and defaults to `True`.
    """

    previous = BooleanProperty(False)
    """
    Shows only image previews.

    :attr:`previous` is an :class:`~kivy.properties.BooleanProperty`
    and defaults to `False`.
    """

    _window_manager = None
    _window_manager_open = False

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.history = []  # directory navigation history
        # If False - do not add a directory to the history -
        # The user moves down the tree.
        self.history_flag = True
        toolbar_label = self.ids.toolbar.children[1].children[0]
        toolbar_label.font_style = "Subtitle1"
        self.ext = [".png", ".jpg", ".jpeg"]
        self.app = App.get_running_app()
        if not os.path.exists(os.path.join(self.app.user_data_dir, "thumb")):
            os.mkdir(os.path.join(self.app.user_data_dir, "thumb"))
        action_button = FloatButton(
            callback=self.select_directory_on_press_button,
            md_bg_color=self.theme_cls.primary_color,
            icon=self.icon,
        )
        self.add_widget(action_button)

    def show(self, path):
        """Forms the body of a directory tree.

        :param path: The path to the directory that will be opened in the file manager.
        """

        dirs, files = self.get_content(path)

        if self.previous:
            threading.Thread(target=self._create_previous, args=(path,)).start()
            split_dirs = self._split_list(dirs, 3)
            split_files = self._split_list(files, 3)

        self.current_path = path
        manager_list = []

        if dirs == [] and files == []:  # selected directory
            pass
        elif not dirs and not files:  # directory is unavailable
            return

        if self.previous:
            for list_dirs in split_dirs:
                manager_list.append(
                    {
                        "viewclass": "BodyManagerWithPrevious",
                        "path": path,
                        "icon_folder": self.icon_folder,
                        "paths": list_dirs,
                        "type": "folder",
                        "events_callback": self.select_dir_or_file,
                        "height": dp(105),
                    }
                )
            for list_files in list(split_files):
                manager_list.append(
                    {
                        "viewclass": "BodyManagerWithPrevious",
                        "path": path,
                        "icon_folder": self.icon_folder,
                        "paths": list_files,
                        "type": "files",
                        "events_callback": self.select_dir_or_file,
                        "height": dp(105),
                    }
                )
        else:
            for name in dirs:
                _path = path + name if path == "/" else path + "/" + name
                access_string = self.get_access_string(_path)
                if "r" not in access_string:
                    icon = "folder-lock"
                else:
                    icon = "folder"

                manager_list.append(
                    {
                        "viewclass": "BodyManager",
                        "path": _path,
                        "icon": icon,
                        "dir_or_file_name": name,
                        "events_callback": self.select_dir_or_file,
                    }
                )
            for name in files:
                _path = path + name if path == "/" else path + "/" + name
                manager_list.append(
                    {
                        "viewclass": "BodyManager",
                        "path": _path,
                        "icon": "file-outline",
                        "dir_or_file_name": name,
                        "events_callback": self.select_dir_or_file,
                    }
                )
        self.ids.rv.data = manager_list

        if not self._window_manager:
            self._window_manager = ModalView(
                size_hint=(1, 1), auto_dismiss=False
            )
            self._window_manager.add_widget(self)
        if not self._window_manager_open:
            self._window_manager.open()
            self._window_manager_open = True

    def count_ext(self, path):
        ext = os.path.splitext(path)[1]
        if ext != "":
            if ext.lower() in self.ext or ext.upper() in self.ext:
                return True
        return False

    def get_access_string(self, path):
        access_string = ""
        if self.use_access:
            access_data = {"r": os.R_OK, "w": os.W_OK, "x": os.X_OK}
            for access in access_data.keys():
                access_string += (
                    access if os.access(path, access_data[access]) else "-"
                )
        return access_string

    def get_content(self, path):
        """Returns a list of the type [[Folder List], [file list]]."""

        try:
            files = []
            dirs = []

            if self.history_flag:
                self.history.append(path)
            if not self.history_flag:
                self.history_flag = True

            for content in os.listdir(path):
                if os.path.isdir(os.path.join(path, content)):
                    if self.search == "all" or self.search == "dirs":
                        dirs.append(content)
                else:
                    if self.search == "all" or self.search == "files":
                        if len(self.ext) != 0:
                            try:
                                if self.count_ext(content):
                                    if self.previous:
                                        files.append(
                                            os.path.join(
                                                self.app.user_data_dir,
                                                "thumb",
                                                f"thumb_{content}",
                                            )
                                        )
                                    else:
                                        files.append(content)
                            except IndexError:
                                pass
                        else:
                            files.append(content)
            return dirs, files
        except OSError:
            self.history.pop()
            return None, None

    def close(self):
        """Closes the file manager window."""

        self._window_manager.dismiss()
        self._window_manager_open = False

    def select_dir_or_file(self, path):
        """Called by tap on the name of the directory or file."""

        if os.path.isfile(path):
            self.select_path(path)
            return

        self.current_path = path
        self.show(path)

    def back(self):
        """Returning to the branch down in the directory tree."""

        if len(self.history) == 1:
            path, end = os.path.split(self.history[0])
            if end == "":
                self.close()
                self.exit_manager(1)
                return
            self.history[0] = path
        else:
            self.history.pop()
            path = self.history[-1]
        self.history_flag = False
        self.select_dir_or_file(path)

    def select_directory_on_press_button(self, *args):
        """Called when a click on a floating button."""

        self.select_path(self.current_path)

    def _update_list_images(self):
        self.ids.rv.refresh_from_layout()

    def _split_list(self, l, n):
        if l:
            n = max(1, n)
            return (l[i : i + n] for i in range(0, len(l), n))
        else:
            return []

    def _create_previous(self, path):
        if "r" not in self.get_access_string(path):
            toast("PermissionError")
            return
        for image in os.listdir(path):
            _path = os.path.join(path, image)
            if os.path.isfile(_path):
                if self.count_ext(_path):
                    path_to_thumb = os.path.join(
                        self.app.user_data_dir, "thumb", f"thumb_{image}"
                    )
                    if not os.path.exists(path_to_thumb):
                        im = Image.open(_path)
                        im.thumbnail((200, 200))
                        im.save(path_to_thumb, "PNG")
Пример #51
0
    def show(self, path):
        """Forms the body of a directory tree.

        :param path:
            The path to the directory that will be opened in the file manager.
        """

        self.current_path = path
        self.selection = []
        dirs, files = self.get_content()
        manager_list = []

        if dirs == [] and files == []:  # selected directory
            pass
        elif not dirs and not files:  # directory is unavailable
            return

        if self.preview:
            for name_dir in self.__sort_files(dirs):
                manager_list.append({
                    "viewclass": "BodyManagerWithPreview",
                    "path": self.icon_folder,
                    "realpath": os.path.join(path),
                    "type": "folder",
                    "name": name_dir,
                    "events_callback": self.select_dir_or_file,
                    "height": dp(150),
                    "_selected": False,
                })
            for name_file in self.__sort_files(files):
                if (os.path.splitext(os.path.join(path, name_file))[1]
                        in self.ext):
                    manager_list.append({
                        "viewclass": "BodyManagerWithPreview",
                        "path": os.path.join(path, name_file),
                        "name": name_file,
                        "type": "files",
                        "events_callback": self.select_dir_or_file,
                        "height": dp(150),
                        "_selected": False,
                    })
        else:
            for name in self.__sort_files(dirs):
                _path = os.path.join(path, name)
                access_string = self.get_access_string(_path)
                if "r" not in access_string:
                    icon = "folder-lock"
                else:
                    icon = "folder"

                manager_list.append({
                    "viewclass": "BodyManager",
                    "path": _path,
                    "icon": icon,
                    "dir_or_file_name": name,
                    "events_callback": self.select_dir_or_file,
                    "_selected": False,
                })
            for name in self.__sort_files(files):
                if self.ext and os.path.splitext(name)[1] not in self.ext:
                    continue

                manager_list.append({
                    "viewclass": "BodyManager",
                    "path": name,
                    "icon": "file-outline",
                    "dir_or_file_name": os.path.split(name)[1],
                    "events_callback": self.select_dir_or_file,
                    "_selected": False,
                })
        self.ids.rv.data = manager_list

        if not self._window_manager:
            self._window_manager = ModalView(size_hint=(1, 1),
                                             auto_dismiss=False)
            self._window_manager.add_widget(self)
        if not self._window_manager_open:
            self._window_manager.open()
            self._window_manager_open = True
Пример #52
0
class MDFileManager(ThemableBehavior, MDFloatLayout):
    icon = StringProperty("check")
    """
    The icon that will be used on the directory selection button.

    :attr:`icon` is an :class:`~kivy.properties.StringProperty`
    and defaults to `check`.
    """

    icon_folder = StringProperty(f"{images_path}folder.png")
    """
    The icon that will be used for folder icons when using ``preview = True``.

    :attr:`icon` is an :class:`~kivy.properties.StringProperty`
    and defaults to `check`.
    """

    exit_manager = ObjectProperty(lambda x: None)
    """
    Function called when the user reaches directory tree root.

    :attr:`exit_manager` is an :class:`~kivy.properties.ObjectProperty`
    and defaults to `lambda x: None`.
    """

    select_path = ObjectProperty(lambda x: None)
    """
    Function, called when selecting a file/directory.

    :attr:`select_path` is an :class:`~kivy.properties.ObjectProperty`
    and defaults to `lambda x: None`.
    """

    ext = ListProperty()
    """
    List of file extensions to be displayed in the manager.
    For example, `['.py', '.kv']` - will filter out all files,
    except python scripts and Kv Language.

    :attr:`ext` is an :class:`~kivy.properties.ListProperty`
    and defaults to `[]`.
    """

    search = OptionProperty("all", options=["all", "dirs", "files"])
    """
    It can take the values 'all' 'dirs' 'files' - display only directories
    or only files or both them. By default, it displays folders, and files.
    Available options are: `'all'`, `'dirs'`, `'files'`.

    :attr:`search` is an :class:`~kivy.properties.OptionProperty`
    and defaults to `all`.
    """

    current_path = StringProperty(os.getcwd())
    """
    Current directory.

    :attr:`current_path` is an :class:`~kivy.properties.StringProperty`
    and defaults to `/`.
    """

    use_access = BooleanProperty(True)
    """
    Show access to files and directories.

    :attr:`use_access` is an :class:`~kivy.properties.BooleanProperty`
    and defaults to `True`.
    """

    preview = BooleanProperty(False)
    """
    Shows only image previews.

    :attr:`preview` is an :class:`~kivy.properties.BooleanProperty`
    and defaults to `False`.
    """

    show_hidden_files = BooleanProperty(False)
    """
    Shows hidden files.

    :attr:`show_hidden_files` is an :class:`~kivy.properties.BooleanProperty`
    and defaults to `False`.
    """

    sort_by = OptionProperty(
        "name", options=["nothing", "name", "date", "size", "type"])
    """
    It can take the values 'nothing' 'name' 'date' 'size' 'type' - sorts files by option
    By default, sort by name.
    Available options are: `'nothing'`, `'name'`, `'date'`, `'size'`, `'type'`.

    :attr:`sort_by` is an :class:`~kivy.properties.OptionProperty`
    and defaults to `name`.
    """

    sort_by_desc = BooleanProperty(False)
    """
    Sort by descending.

    :attr:`sort_by_desc` is an :class:`~kivy.properties.BooleanProperty`
    and defaults to `False`.
    """

    selector = OptionProperty("any",
                              options=["any", "file", "folder", "multi"])
    """
    It can take the values 'any' 'file' 'folder' 'multi'
    By default, any.
    Available options are: `'any'`, `'file'`, `'folder'`, `'multi'`.

    :attr:`selector` is an :class:`~kivy.properties.OptionProperty`
    and defaults to `any`.
    """

    selection = ListProperty()
    """
    Contains the list of files that are currently selected.

    :attr:`selection` is a read-only :class:`~kivy.properties.ListProperty` and
    defaults to `[]`.
    """

    _window_manager = None
    _window_manager_open = False

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

        toolbar_label = self.ids.toolbar.children[1].children[0]
        toolbar_label.font_style = "Subtitle1"

        if (self.selector == "any" or self.selector == "multi"
                or self.selector == "folder"):
            self.add_widget(
                FloatButton(
                    callback=self.select_directory_on_press_button,
                    md_bg_color=self.theme_cls.primary_color,
                    icon=self.icon,
                ))

        if self.preview:
            self.ext = [".png", ".jpg", ".jpeg"]

    def __sort_files(self, files):
        def sort_by_name(files):
            files.sort(key=locale.strxfrm)
            files.sort(key=str.casefold)

            return files

        if self.sort_by == "name":
            sorted_files = sort_by_name(files)

        elif self.sort_by == "date":
            _files = sort_by_name(files)
            _sorted_files = [
                os.path.join(self.current_path, f) for f in _files
            ]
            _sorted_files.sort(key=os.path.getmtime, reverse=True)

            sorted_files = [os.path.basename(f) for f in _sorted_files]

        elif self.sort_by == "size":
            _files = sort_by_name(files)
            _sorted_files = [
                os.path.join(self.current_path, f) for f in _files
            ]
            _sorted_files.sort(key=os.path.getsize, reverse=True)

            sorted_files = [os.path.basename(f) for f in _sorted_files]

        elif self.sort_by == "type":
            _files = sort_by_name(files)

            sorted_files = sorted(
                _files,
                key=lambda f: (os.path.splitext(f)[1], os.path.splitext(f)[0]),
            )

        else:
            sorted_files = files

        if self.sort_by_desc:
            sorted_files.reverse()

        return sorted_files

    def show(self, path):
        """Forms the body of a directory tree.

        :param path:
            The path to the directory that will be opened in the file manager.
        """

        self.current_path = path
        self.selection = []
        dirs, files = self.get_content()
        manager_list = []

        if dirs == [] and files == []:  # selected directory
            pass
        elif not dirs and not files:  # directory is unavailable
            return

        if self.preview:
            for name_dir in self.__sort_files(dirs):
                manager_list.append({
                    "viewclass": "BodyManagerWithPreview",
                    "path": self.icon_folder,
                    "realpath": os.path.join(path),
                    "type": "folder",
                    "name": name_dir,
                    "events_callback": self.select_dir_or_file,
                    "height": dp(150),
                    "_selected": False,
                })
            for name_file in self.__sort_files(files):
                if (os.path.splitext(os.path.join(path, name_file))[1]
                        in self.ext):
                    manager_list.append({
                        "viewclass": "BodyManagerWithPreview",
                        "path": os.path.join(path, name_file),
                        "name": name_file,
                        "type": "files",
                        "events_callback": self.select_dir_or_file,
                        "height": dp(150),
                        "_selected": False,
                    })
        else:
            for name in self.__sort_files(dirs):
                _path = os.path.join(path, name)
                access_string = self.get_access_string(_path)
                if "r" not in access_string:
                    icon = "folder-lock"
                else:
                    icon = "folder"

                manager_list.append({
                    "viewclass": "BodyManager",
                    "path": _path,
                    "icon": icon,
                    "dir_or_file_name": name,
                    "events_callback": self.select_dir_or_file,
                    "_selected": False,
                })
            for name in self.__sort_files(files):
                if self.ext and os.path.splitext(name)[1] not in self.ext:
                    continue

                manager_list.append({
                    "viewclass": "BodyManager",
                    "path": name,
                    "icon": "file-outline",
                    "dir_or_file_name": os.path.split(name)[1],
                    "events_callback": self.select_dir_or_file,
                    "_selected": False,
                })
        self.ids.rv.data = manager_list

        if not self._window_manager:
            self._window_manager = ModalView(size_hint=(1, 1),
                                             auto_dismiss=False)
            self._window_manager.add_widget(self)
        if not self._window_manager_open:
            self._window_manager.open()
            self._window_manager_open = True

    def get_access_string(self, path):
        access_string = ""
        if self.use_access:
            access_data = {"r": os.R_OK, "w": os.W_OK, "x": os.X_OK}
            for access in access_data.keys():
                access_string += (access if os.access(
                    path, access_data[access]) else "-")
        return access_string

    def get_content(self):
        """Returns a list of the type [[Folder List], [file list]]."""

        try:
            files = []
            dirs = []

            for content in os.listdir(self.current_path):
                if os.path.isdir(os.path.join(self.current_path, content)):
                    if self.search == "all" or self.search == "dirs":
                        if (not self.show_hidden_files) and (
                                content.startswith(".")):
                            continue
                        else:
                            dirs.append(content)

                else:
                    if self.search == "all" or self.search == "files":
                        if len(self.ext) != 0:
                            try:
                                files.append(
                                    os.path.join(self.current_path, content))
                            except IndexError:
                                pass
                        else:
                            if (not self.show_hidden_files
                                    and content.startswith(".")):
                                continue
                            else:
                                files.append(content)

            return dirs, files

        except OSError:
            return None, None

    def close(self):
        """Closes the file manager window."""

        self._window_manager.dismiss()
        self._window_manager_open = False

    def select_dir_or_file(self, path, widget):
        """Called by tap on the name of the directory or file."""

        if os.path.isfile(os.path.join(self.current_path, path)):
            if self.selector == "multi":
                file_path = os.path.join(self.current_path, path)
                if file_path in self.selection:
                    widget._selected = False
                    self.selection.remove(file_path)
                else:
                    widget._selected = True
                    self.selection.append(file_path)
            elif self.selector == "folder":
                return
            else:
                self.select_path(os.path.join(self.current_path, path))

        else:
            self.current_path = path
            self.show(path)

    def back(self):
        """Returning to the branch down in the directory tree."""

        path, end = os.path.split(self.current_path)

        if not end:
            self.close()
            self.exit_manager(1)

        else:
            self.show(path)

    def select_directory_on_press_button(self, *args):
        """Called when a click on a floating button."""

        if self.selector == "multi":
            if len(self.selection) > 0:
                self.select_path(self.selection)
        else:
            if self.selector == "folder" or self.selector == "any":
                self.select_path(self.current_path)
Пример #53
0
 def show_add_customer(self):
     view = ModalView(size_hint=(None, None), size=(400,250), auto_dismiss =True)
     view.add_widget(CustomerSave())
     view.open()
Пример #54
0
def show_winner(board):
    popup = ModalView(size_hint=(0.75, 0.5))
    victory_label = Label(text="You won!", font_size=50)
    popup.add_widget(victory_label)
    popup.bind(on_dismiss=board.on_win)
    popup.open()
Пример #55
0
 def on_touch_down(self, touch):
     if self.collide_point(touch.x, touch.y):
         view = ModalView(size_hint=(None, None), size=(600, 400))
         #view.add_widget(RedditLink(text=self.text,thumbnail=self.thumbnail,ups=self.ups,source=self.source,color=self.color))
         view.add_widget(AsyncImage(source=self.url))
         view.open()
Пример #56
0
class AnkiCardGenApp(MDApp):
    """Main App."""

    # Data
    template = ObjectProperty(force_dispatch=True)

    # Config
    apkg_export_dir = ConfigParserProperty(
        HOME / "ankicardgen",
        "Paths",
        "apkg_export_dir",
        "app",
    )
    import_dir = ConfigParserProperty(HOME, "Paths", "import_dir", "app")
    kobo_import_dir = ConfigParserProperty(HOME, "Paths", "kobo_import_dir",
                                           "app")
    anki_template_dir = ConfigParserProperty("vocab_card", "Paths",
                                             "anki_template_dir", "app")
    anki_deck_name = ConfigParserProperty("Portuguese::Vocab", "Anki",
                                          "deck_name", "app")
    primary_palette = ConfigParserProperty("Red", "Theme", "primary_palette",
                                           "app")
    accent_palette = ConfigParserProperty("Amber", "Theme", "accent_palette",
                                          "app")
    theme_style = ConfigParserProperty("Light", "Theme", "theme_style", "app")
    source_language = ConfigParserProperty("en", "Template", "source_language",
                                           "app")
    target_language = ConfigParserProperty("pt", "Template", "target_language",
                                           "app")
    current_template_name = ConfigParserProperty("Portuguese Vocabulary (en)",
                                                 "Template", "name", "app")
    # TODO: fix bug where default value has to be a valid recipe
    templates = AliasProperty(
        getter=lambda *_: template_cookbook.get_recipe_names())

    word_state_dict = DictProperty()

    busy = BooleanProperty(False)
    busy_modal = ObjectProperty(None)

    file_manager = ObjectProperty(None)
    dropdown_menu = ObjectProperty(None)

    def get_anki_template_dir(self):
        """Return absolute path where html-, css- and js-files for anki-card is located."""
        return os.path.join(ANKI_DIR, self.anki_template_dir)

    @staticmethod
    def get_application_config():
        """Return default path for the config."""
        return str(CONFIG_PATH)

    def build_config(self, config):  # pylint: disable=no-self-use
        """If no config-file exists, sets the default."""
        config.setdefaults(
            "Theme",
            {
                "primary_palette": "Red",
                "accent_palette": "Amber",
                "theme_style": "Light",
            },
        )
        config.setdefaults("Paths", {})

    def bind_theme_cls_and_config(self):
        """Bind :attr:`theme_cls` and the corresponding :class:`~kivy.properties.ConfigParserProperties`."""
        keys = self.config["Theme"]
        self.bind(**{key: self.theme_cls.setter(key) for key in keys})
        self.theme_cls.bind(**{key: self.setter(key) for key in keys})
        for key in keys:
            setattr(self.theme_cls, key, getattr(self, key))

    def build(self):
        """Set up App and return :class:`custom_widgets.MainMenu` as root widget."""
        self.bind_theme_cls_and_config()
        self.file_manager = MDFileManager()
        Config.set("input", "mouse", "mouse,disable_multitouch")
        os.makedirs(self.apkg_export_dir, exist_ok=True)
        return MainMenu(
            screen_dicts=screens.screen_dicts,
            screen_dir=str(screens.SCREEN_DIR),
            image_source=str(ASSETS_DIR / "AnkiCardGen.png"),
        )

    @db_session
    def get_current_template_db(self):
        """Return data-base object for :attr:`current_template_name`."""
        return db.Template.get(name=self.current_template_name) or db.Template(
            name=self.current_template_name)

    def get_word_states(self):
        """Return dict of word-states for current template from data-base."""
        with db_session:
            return {
                card.name: card.state
                for card in self.get_current_template_db().cards
            }

    def new_template_instance(self):
        """Return new instance of current template class."""
        return template_cookbook.cook(self.current_template_name)

    def on_current_template_name(self, *_):
        """Set up new template if :attr:`current_template_name` changes."""
        self.template = self.new_template_instance()
        self.word_state_dict = self.get_word_states()

    def on_start(self):
        """Set up template on start of app."""
        super().on_start()
        self.on_current_template_name()
        self.request_permissions()

    def on_pause(self):  # pylint: disable=no-self-use
        """Enable coming back to app."""
        return True

    @mainthread
    def on_busy(self, *_):
        """Set up :attr:`busy_modal` if necessary. Then open or close it depending on state of :attr:`busy`."""
        if not self.busy_modal:
            self.busy_modal = ModalView(
                auto_dismiss=False,
                size_hint=(1.2, 1.2),
                opacity=0.5,
            )
            spinner = MDSpinner(active=False, size_hint=(0.5, 0.5))
            self.busy_modal.add_widget(spinner)
            self.bind(busy=spinner.setter("active"))
        if self.busy:
            self.busy_modal.open()
        else:
            self.busy_modal.dismiss()

    @staticmethod
    def request_permissions():
        """Request storage permissions on android."""
        if platform == "android":
            from android.permissions import (  # pylint: disable=import-outside-toplevel
                Permission, request_permissions,
            )

            request_permissions([
                Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE
            ])
Пример #57
0
class rootEngine(FloatLayout):

    #    def mp(self,mn):
    #        # {
    #        def __init__(**kwargs):
    #            super(mp,self).__init__(self)
    #
    #        def lambida(object):
    #            lambda mn, mn * mn // .2 ## get power
    #
    #        def squary(object):
    #            lambda mn: mn ** mn / 2
    # }

    # just some dictionaries below

    def __init__(self, **kwargs):
        """
        Main Engine
        """
        super(rootEngine, self).__init__(**kwargs)
        self.rstView(name="coreEngine/Rst/index.rst")
        self.Config = None
        self.savedSource = ""  # None Immutable
        self.current = ""  # None Immutable
        _savedInts = open("coreEngine/Rst/saved.ctex", "r")
        self.saved = 0
        self.savedMake = 0
        self.iterSaved = 0
        self.toMakeSaved = None
        self.coreTexMimes = {
            "index": "coreEngine/Rst/index.rst",
            "code": "coreEngine/Rst/code.rst",
            "help": "coreEngine/Rst/help.rst",
            "new": "coreEngine/Rst/new.rst",
            "web": "coreEngine/Rst/web.rst",
            "cache": "coreEngine/Rst/cache.rst",
            "saved": "coreEngine/Rst/saved.ctex",
            "cleared": "coreEngine/Rst/cleared.rst",
        }  # .rst = ReST File ,  .ctex = CoreTEX File

    def getLatestSaved(self):
        _openFile = open(self.coreTexMimes["saved"],
                         "r")  # .ctex is the Mimetype for the CoreTEX File
        _contents = _openFile.read()
        _openFile.close()
        #if _openFile.close():
        eval_isDangerous = eval(_contents)
        for Ints in eval_isDangerous:
            Latest = int(max(eval_isDangerous))  # Latest Enumeration
            Iterable = list(eval_isDangerous)  # List / Array
            break
        self.saved = Latest
        self.iterSaved = Iterable

    def reloadCode(self):
        """
        reload Compiler
        """
        self.rstView(name=str(self.current))

    def loadRemotely(self):
        """
        Load Remotely (web)
        """
        toDownload = ""
        main = Popup(title="Load .RST Document Remotely", size_hint=(.9, .4))
        layer = FloatLayout()
        cancelBtn = Button(text="Cancel",
                           size_hint=(.4, .12),
                           pos_hint={
                               "x": .10,
                               "y": 0.04
                           })  # 100% - hint (divide if needed)
        openBtn = Button(text="Load",
                         size_hint=(.4, .12),
                         pos_hint={
                             "x": .50,
                             "y": 0.04
                         })
        desc = "Make sure to load a raw RST Source"
        descWid = Label(text=str(desc),
                        size_hint=(.4, .4),
                        pos_hint={
                            "x": 0.30,
                            "y": 0.50
                        })
        url_box = TextInput(text="http://",
                            size_hint=(.8, 0.15),
                            pos_hint={
                                "x": 0.10,
                                "y": 0.24
                            },
                            multiline=False)

        def closePop(object):
            """
            Close Popups
            INNER FUNC
            """
            main.dismiss()

        def LabelError(object):
            """
            Exception Message
            INNER FUNC
            """
            main.title = "Please Recheck the URL"

        def web_Get(object):
            """
            get rst source via Web
            INNER FUNC
            """
            _string_url = str(url_box.text)

            def check_Rst(filer):
                from pygments.lexers.text import RstLexer  #

                file_to_check = str(filer)
                return RstLexer.analyse_text(file_to_check)

            try:
                webEmu = urllib.urlopen(_string_url)
                response = webEmu.read()
                #if "http://" not in _string_url:
                #    print "error"
                #    return False
                #elif "https://" not in _string_url:
                #    print "error"
                #    return False
                #_fixed_url = "https://{web}".format(web=_string_url) #SSL Protocol
                #else:
                #    _fixed_url = "{web}".format(web=_string_url) # clean yet with error i guess.

            except Exception:
                main.title = "Error, Please recheck the Url! or your Connection"
                url_box.text = "http://"
                return False

            main.title = "Source has been Loaded to Editor Successfully"
            web_cache_file = open("coreEngine/Rst/web.rst", "w")
            web_cache_file.write(str(response))
            web_cache_file.close()
            if len(str(response)) <= 3:
                main.title = "File from Web has Unsufficient bytes"

            else:
                self.current = self.coreTexMimes["web"]

                try:
                    self.rstView(name="coreEngine/Rst/web.rst")
                    #self.ids.core.source = "coreEngine/Rst/web.rst"
                except:
                    main.title = "File Not Loaded: Parsing Returns Error"
            main.dismiss()

        cancelBtn.bind(on_release=closePop)
        openBtn.bind(on_press=web_Get)

        layer.add_widget(url_box)
        layer.add_widget(cancelBtn)
        layer.add_widget(openBtn)
        layer.add_widget(descWid)
        main.add_widget(layer)
        main.open()

    def Loader_NoErr(self, ctexSaved, fixedPath):
        import os
        with open(ctexSaved) as f:
            Source_read = f.read()
        self.current = self.coreTexMimes["saved"]
        self.rstView(name=str(fixedPath))

    def Load(self):
        """
        Load from the Disk
        Button > Load()
        """
        from functools import partial
        from kivy.uix import filechooser
        from kivy.uix.filechooser import FileChooserListView, FileChooserIconView
        main = ModalView(size_hint=(.8, .8))  # everything on this Modal is 80%
        BL = BoxLayout(portrait="vertical")

        FLV = FileChooserListView(path="coreEngine/Saved", )

        def cTexloader(instance):
            Selected = FLV.selection
            Selected_Attr = Selected
            LStoString = str(Selected_Attr[0])
            self.Loader_NoErr(ctexSaved=LStoString, fixedPath=LStoString)

        Load_Btn = Button(text="Load this File")
        Load_Btn.bind(on_press=cTexloader)
        main.add_widget(BL)
        BL.add_widget(FLV)
        BL.add_widget(Load_Btn)

        main.open()

    def createNew(self):
        """
        Create New File [Button]
        """
        try:
            savedLists = open("coreEngine/Rst/saved.ctex",
                              "r")  # Saved Pattern file ....
            lastSaved = savedLists.read()
            size_val = eval(str(lastSaved))
            to_create = len(size_val)
            cache_Files = {
                "file": "{name}.rst".format(name=int(to_create) + 1),
                "number": str(int(to_create) + 1)
            }
            self.ids.core.source = "coreEngine/Rst/new.rst"
        except:
            self.ids.core.text = "Error Occured processing New File!"
        finally:
            self.currentCache_file = cache_Files["file"]
            self.currentCache_int = cache_Files["number"]
            savedLists.close()
            self.current = "new.rst"

    def clear(self):
        from coreEngine.Libraries import createlib
        """
        Clear Editor func
        """
        if len(self.ids.core.text) > 1:
            self.current = self.coreTexMimes["cleared"]
            self.ids.core.source = "coreEngine/Rst/cleared.rst"
        else:
            pass

    def webShareAPI(self):
        """
        using pastebin-API to send and save on web!
        """
        pass

    def SendEmail(self):
        """
        send the source to any Email func
        """
        self.getLatestSaved()

    def helpView(self):
        """
        Show Help/Guides modal (show when help button pressed)
        """
        widgets = FloatLayout(
            size_hint=(None, None),
            size=(300, 300),
            background_color=parse_color("#FF9933"),
        )
        sizer = NumericProperty(30)
        main = ModalView(
            title_color=parse_color("#FF9933"),
            title_size=(25),
            seperator_height=("9dp"),
            separator_color=parse_color("#FF9933"),
            #background_color=parse_color("#FF9933"),
            size_hint=(None, None),
            size=(400, 620),
            content=Image(source="coreEngine/Images/about.png"),
        )

        white_bar = Image(source="coreEngine/Images/whitebar.png",
                          pos=(123, 123),
                          size=(400, 400))

        logo = Image(source="coreEngine/Images/about.png")

        main.add_widget(logo, 1)
        main.open()

##  FUNCTION

    def rstView(self, name=""):
        """
        Return Code into Parser
        """
        self.ids.core.source = name  #simple as dat.

##  FUNCTION

    def TweakView(self):
        """
        Tweak Settings / Color etc.
        """
        pass


##  FUNCTION

    def SettingView(self):
        """
        Settings View / Options whatsoever
        """
        self.closeChecker()

    def compileView(self):
        """
        once the source has been sent from compiler, it will show the parsed version of the source
        """
        try:
            self.ids.core.source = self.current
        except Exception:
            print "error"

    def sourceView(self):
        """
        lemme show your the source!
        """
        def subFunction_Divisor(object):
            lambda xy: xy**xy // 3  # get the Power and return Divided in Floor Division

        self.main = ModalView(size_hint=(None, None), size=(420, 750))

        self.modalMain = FloatLayout()
        self.saveButton = Button(text="Save",
                                 size_hint=(None, None),
                                 size=(100, 40),
                                 pos=(320, 30))
        self.cancelButton = Button(text="Cancel",
                                   size_hint=(None, None),
                                   size=(100, 40),
                                   pos=(60, 30))
        self.head = Label(text="CoreTEX Source",
                          size_hint=(None, None),
                          pos=(60, 700))
        self.box = CodeInput(size_hint=(None, None),
                             size=(390, 650),
                             pos=(45, 77),
                             use_bubble=True)  #editor in modal view#
        self.box.text = str(self.ids.core.text)

        def cancelAll(instance):
            """
            self.main close trigger
            """
            self.main.dismiss()

        def saveAll(instance):
            """
            Load Cache.rst (Cache File from the coreEngine)
            everything will be saved as Cache... (Editable on Options)
            """
            cur = self.ids.core.source
            if "index.rst" in str(cur):
                self.main.dismiss(
                )  #dont ever let the editor edit this file :P
                return False

            if "new" in self.current:
                self.getLatestSaved()  # Run to get Eval code
                # load file
                _file = open(self.coreTexMimes["saved"], "rw+")
                _read = _file.read()
                # load file
                curCache = int(self.saved)
                cache_value = lambda ctex: ctex + 1
                cache_final = cache_value(curCache)
                return False

            box_strings = str(self.box.text)
            current = self.current  # add this on the Current working file
            cache_file_open = open("coreEngine/Rst/cache.rst", "w")
            cache_file_writeNow = cache_file_open.write(box_strings)
            cache_file_open.close()

            if cache_file_open.closed:
                pass  # Do everything here

            else:
                cancelAll()

        # lambda gbox:
        self.saveButton.bind(on_press=saveAll)
        self.cancelButton.bind(on_press=cancelAll)
        self.modalMain.add_widget(self.box)
        self.modalMain.add_widget(self.head)
        self.modalMain.add_widget(self.cancelButton)
        self.modalMain.add_widget(self.saveButton)
        self.main.add_widget(self.modalMain)
        #main.add_widget(cancelButton)
        self.main.open()

    def AnimateStart(self):
        """
        Animator :) Useless.
        """
        from kivy.animation import Animation

        LOL = Animation(x=50, size=(200, 200), t='in_quad')
        LOL.start(self.ids.startme), self.rstView()

    def closeChecker(self):  # call me when needed :3
        """
        Func to do
        If file is Opened, make it close,
        Else file is Closed, do Nothing.
        """
        # constants hack hahaha
        check_1, check_2, check_3, check_4, check_5, check_6, check_7 = 1, 1, 1, 1, 1, 1, 1
        if bool(check_1):
            try:
                file_1 = open(self.coreTexMimes["index"], "r")
            except IOError:
                check_1 = 0
        if bool(check_2):
            try:
                file_2 = open(self.coreTexMimes["code"], "r")
            except IOError:
                check_2 = 0
        if bool(check_3):
            try:
                file_3 = open(self.coreTexMimes["help"], "r")
            except IOError:
                check_3 = 0
        if bool(check_4):
            try:
                file_4 = open(self.coreTexMimes["new"], "r")
            except IOError:
                check_4 = 0
        if bool(check_5):
            try:
                file_5 = open(self.coreTexMimes["web"], "r")
            except IOError:
                check_5 = 0
        if bool(check_6):
            try:
                file_6 = open(self.coreTexMimes["cache"], "r")
            except IOError:
                check_6 = 0
        if bool(check_7):
            try:
                file_7 = open(self.coreTexMimes["saved"], "r")
            except IOError:
                check_7 = 0
        check_1, check_2, check_3, check_4, check_5, check_6, check_7 = 1, 1, 1, 1, 1, 1, 1
Пример #58
0
    def sourceView(self):
        """
        lemme show your the source!
        """
        def subFunction_Divisor(object):
            lambda xy: xy**xy // 3  # get the Power and return Divided in Floor Division

        self.main = ModalView(size_hint=(None, None), size=(420, 750))

        self.modalMain = FloatLayout()
        self.saveButton = Button(text="Save",
                                 size_hint=(None, None),
                                 size=(100, 40),
                                 pos=(320, 30))
        self.cancelButton = Button(text="Cancel",
                                   size_hint=(None, None),
                                   size=(100, 40),
                                   pos=(60, 30))
        self.head = Label(text="CoreTEX Source",
                          size_hint=(None, None),
                          pos=(60, 700))
        self.box = CodeInput(size_hint=(None, None),
                             size=(390, 650),
                             pos=(45, 77),
                             use_bubble=True)  #editor in modal view#
        self.box.text = str(self.ids.core.text)

        def cancelAll(instance):
            """
            self.main close trigger
            """
            self.main.dismiss()

        def saveAll(instance):
            """
            Load Cache.rst (Cache File from the coreEngine)
            everything will be saved as Cache... (Editable on Options)
            """
            cur = self.ids.core.source
            if "index.rst" in str(cur):
                self.main.dismiss(
                )  #dont ever let the editor edit this file :P
                return False

            if "new" in self.current:
                self.getLatestSaved()  # Run to get Eval code
                # load file
                _file = open(self.coreTexMimes["saved"], "rw+")
                _read = _file.read()
                # load file
                curCache = int(self.saved)
                cache_value = lambda ctex: ctex + 1
                cache_final = cache_value(curCache)
                return False

            box_strings = str(self.box.text)
            current = self.current  # add this on the Current working file
            cache_file_open = open("coreEngine/Rst/cache.rst", "w")
            cache_file_writeNow = cache_file_open.write(box_strings)
            cache_file_open.close()

            if cache_file_open.closed:
                pass  # Do everything here

            else:
                cancelAll()

        # lambda gbox:
        self.saveButton.bind(on_press=saveAll)
        self.cancelButton.bind(on_press=cancelAll)
        self.modalMain.add_widget(self.box)
        self.modalMain.add_widget(self.head)
        self.modalMain.add_widget(self.cancelButton)
        self.modalMain.add_widget(self.saveButton)
        self.main.add_widget(self.modalMain)
        #main.add_widget(cancelButton)
        self.main.open()
Пример #59
0
class KitchenSink(App, Screens):
    theme_cls = ThemeManager()
    theme_cls.primary_palette = 'Blue'
    previous_date = ObjectProperty()
    title = "Kitchen Sink"
    theme_cls.primary_palette = 'Blue'

    # theme_cls.theme_style = 'Dark'

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

        self.menu_items = [{
            'viewclass': 'MDMenuItem',
            'text': 'Example item %d' % i,
            'callback': self.callback_for_menu_items
        } for i in range(15)]
        self.Window = Window
        self.manager = None
        self.md_theme_picker = None
        self.long_dialog = None
        self.input_dialog = None
        self.alert_dialog = None
        self.ok_cancel_dialog = None
        self.long_dialog = None
        self.dialog = None
        self.manager_open = False
        self.cards_created = False
        self.user_card = None
        self.bs_menu_1 = None
        self.bs_menu_2 = None
        self.tick = 0
        self.create_stack_floating_buttons = False
        self.previous_text =\
            "Welcome to the application [b][color={COLOR}]Kitchen Sink"\
            "[/color][/b].\nTo see [b][color={COLOR}]KivyMD[/color][/b] "\
            "examples, open the menu and select from the list the desired "\
            "example\n\n"\
            ""\
            ""\
            "Author - [b][color={COLOR}]Andrés Rodríguez[/color][/b]\n"\
            "[u][b][color={COLOR}][email protected][/color]"\
            "[/b][/u]\n\n"\
            "Author this Fork - [b][color={COLOR}]Ivanov Yuri[/color][/b]\n"\
            "[u][b][color={COLOR}][email protected][/color]"\
            "[/b][u]".format(COLOR=get_hex_from_color(
                self.theme_cls.primary_color))
        self.names_contacts = ('Alexandr Taylor', 'Yuri Ivanov',
                               'Robert Patric', 'Bob Marley', 'Magnus Carlsen',
                               'Jon Romero', 'Anna Bell', 'Maxim Kramerer',
                               'Sasha Gray', 'Vladimir Ivanenko')
        Window.bind(on_keyboard=self.events)
        crop_image(
            (Window.width, int(dp(Window.height * 35 // 100))),
            '{}/assets/guitar-1139397_1280.png'.format(self.directory),
            '{}/assets/guitar-1139397_1280_crop.png'.format(self.directory))

    def crop_image_for_tile(self, instance, size, path_to_crop_image):
        if not os.path.exists(os.path.join(self.directory,
                                           path_to_crop_image)):
            size = (int(size[0]), int(size[1]))
            path_to_origin_image = path_to_crop_image.replace('_tile_crop', '')
            crop_image(size, path_to_origin_image, path_to_crop_image)
        instance.source = path_to_crop_image

    def theme_picker_open(self):
        if not self.md_theme_picker:
            from kivymd.theme_picker import MDThemePicker
            self.md_theme_picker = MDThemePicker()
        self.md_theme_picker.open()

    def example_add_stack_floating_buttons(self):
        from kivymd.stackfloatingbuttons import MDStackFloatingButtons

        def set_my_language(instance_button):
            toast(instance_button.icon)

        if not self.create_stack_floating_buttons:
            screen = self.main_widget.ids.scr_mngr.get_screen('stack buttons')
            screen.add_widget(
                MDStackFloatingButtons(icon='lead-pencil',
                                       floating_data={
                                           'Python': 'language-python',
                                           'Php': 'language-php',
                                           'C++': 'language-cpp'
                                       },
                                       callback=set_my_language))
            self.create_stack_floating_buttons = True

    def set_accordion_list(self):
        from kivymd.accordionlistitem import MDAccordionListItem

        def callback(text):
            toast('{} to {}'.format(text, content.name_item))

        content = ContentForAnimCard(callback=callback)

        for name_contact in self.names_contacts:
            self.accordion_list.ids.anim_list.add_widget(
                MDAccordionListItem(content=content,
                                    icon='assets/kivymd_logo.png',
                                    title=name_contact))

    def set_chevron_back_screen(self):
        """Sets the return chevron to the previous screen in ToolBar."""

        self.main_widget.ids.toolbar.right_action_items = [[
            'dots-vertical', lambda x: self.root.toggle_nav_drawer()
        ]]

    def download_progress_hide(self, instance_progress, value):
        """Hides progress progress."""

        self.main_widget.ids.toolbar.right_action_items =\
            [['download',
              lambda x: self.download_progress_show(instance_progress)]]

    def download_progress_show(self, instance_progress):
        self.set_chevron_back_screen()
        instance_progress.open()
        instance_progress.animation_progress_from_fade()

    def show_example_download_file(self, interval):
        from kivymd.progressloader import MDProgressLoader

        def get_connect(host="8.8.8.8", port=53, timeout=3):
            import socket
            try:
                socket.setdefaulttimeout(timeout)
                socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(
                    (host, port))
                return True
            except (TimeoutError, ConnectionError, OSError):
                return False

        if get_connect():
            link = 'https://www.python.org/ftp/python/3.5.1/'\
                   'python-3.5.1-embed-win32.zip'
            progress = MDProgressLoader(
                url_on_image=link,
                path_to_file=os.path.join(self.directory, 'python-3.5.1.zip'),
                download_complete=self.download_complete,
                download_hide=self.download_progress_hide)
            progress.start(self.download_file.ids.box_flt)
        else:
            toast('Connect error!')

    def download_complete(self):
        self.set_chevron_back_screen()
        toast('Done')

    def file_manager_open(self):
        from kivymd.filemanager import MDFileManager
        from kivymd.dialog import MDDialog

        def open_file_manager(text_item, dialog):
            previous = False if text_item == 'List' else True
            self.manager = ModalView(size_hint=(1, 1), auto_dismiss=False)
            self.file_manager = MDFileManager(exit_manager=self.exit_manager,
                                              select_path=self.select_path,
                                              previous=previous)
            self.manager.add_widget(self.file_manager)
            self.file_manager.show(self.user_data_dir)
            self.manager_open = True
            self.manager.open()

        MDDialog(title='Title',
                 size_hint=(.8, .4),
                 text_button_ok='List',
                 text="Open manager with 'list' or 'previous' mode?",
                 text_button_cancel='Previous',
                 events_callback=open_file_manager).open()

    def select_path(self, path):
        """It will be called when you click on the file name
        or the catalog selection button.

        :type path: str;
        :param path: path to the selected directory or file;

        """

        self.exit_manager()
        toast(path)

    def exit_manager(self, *args):
        """Called when the user reaches the root of the directory tree."""

        self.manager.dismiss()
        self.manager_open = False
        self.set_chevron_menu()

    def set_chevron_menu(self):
        self.main_widget.ids.toolbar.left_action_items = [[
            'menu', lambda x: self.root.toggle_nav_drawer()
        ]]

    def events(self, instance, keyboard, keycode, text, modifiers):
        """Called when buttons are pressed on the mobile device.."""

        if keyboard in (1001, 27):
            if self.manager_open:
                self.file_manager.back()
        return True

    def callback_for_menu_items(self, *args):
        toast(args[0])

    def add_cards(self, instance_grid_card):
        from kivymd.cards import MDCardPost

        def callback(instance, value):
            if value is None:
                toast('Delete post %s' % str(instance))
            elif isinstance(value, int):
                toast('Set like in %d stars' % value)
            elif isinstance(value, str):
                toast('Repost with %s ' % value)
            elif isinstance(value, list):
                toast(value[1])

        if not self.cards_created:
            self.cards_created = True
            menu_items = [{
                'viewclass': 'MDMenuItem',
                'text': 'Example item %d' % i,
                'callback': self.callback_for_menu_items
            } for i in range(2)]
            buttons = ['facebook', 'vk', 'twitter']

            instance_grid_card.add_widget(
                MDCardPost(text_post='Card with text',
                           swipe=True,
                           callback=callback))
            instance_grid_card.add_widget(
                MDCardPost(
                    right_menu=menu_items,
                    swipe=True,
                    text_post='Card with a button to open the menu MDDropDown',
                    callback=callback))
            instance_grid_card.add_widget(
                MDCardPost(likes_stars=True,
                           callback=callback,
                           swipe=True,
                           text_post='Card with asterisks for voting.'))

            instance_grid_card.add_widget(
                MDCardPost(
                    source="./assets/kitten-1049129_1280.png",
                    tile_text="Little Baby",
                    tile_font_style="Headline",
                    text_post="This is my favorite cat. He's only six months "
                    "old. He loves milk and steals sausages :) "
                    "And he likes to play in the garden.",
                    with_image=True,
                    swipe=True,
                    callback=callback,
                    buttons=buttons))

    def update_screen(self, instance):
        def update_screen(interval):
            self.tick += 1
            if self.tick > 2:
                instance.update = True
                self.tick = 0
                self.update_spinner.ids.upd_lbl.text = "New string"
                Clock.unschedule(update_screen)

        Clock.schedule_interval(update_screen, 1)

    main_widget = None

    def build(self):
        self.main_widget = Builder.load_string(main_widget_kv)
        # self.bottom_navigation_remove_mobile(self.main_widget)
        return self.main_widget

    def set_popup_screen(self, content_popup):
        popup_menu = ContentForAnimCard()
        popup_menu.add_widget(Widget(size_hint_y=None, height=dp(150)))
        popup_screen = self.popup_screen.ids.popup_screen
        popup_screen.screen = popup_menu
        popup_screen.background_color = [.3, .3, .3, 1]
        popup_screen.max_height = content_popup.ids.image.height + dp(5)

    def bottom_navigation_remove_mobile(self, widget):
        # Removes some items from bottom-navigation demo when on mobile
        if DEVICE_TYPE == 'mobile':
            widget.ids.bottom_navigation_demo.remove_widget(
                widget.ids.bottom_navigation_desktop_2)
        if DEVICE_TYPE == 'mobile' or DEVICE_TYPE == 'tablet':
            widget.ids.bottom_navigation_demo.remove_widget(
                widget.ids.bottom_navigation_desktop_1)

    def show_user_example_animation_card(self):
        from kivymd.useranimationcard import MDUserAnimationCard

        def main_back_callback():
            toast('Close card')

        if not self.user_card:
            self.user_card = MDUserAnimationCard(
                user_name="Lion Lion",
                path_to_avatar="./assets/guitar-1139397_1280.png",
                callback=main_back_callback)
            self.user_card.box_content.add_widget(ContentForAnimCard())
        self.user_card.open()

    def show_example_snackbar(self, snack_type):
        from kivymd.snackbars import Snackbar

        if snack_type == 'simple':
            Snackbar(text="This is a snackbar!").show()
        elif snack_type == 'button':
            Snackbar(text="This is a snackbar",
                     button_text="with a button!",
                     button_callback=lambda *args: 2).show()
        elif snack_type == 'verylong':
            Snackbar(text="This is a very very very very very very very "
                     "long snackbar!").show()

    def show_example_input_dialog(self):
        def result(text_button, instance):
            toast(instance.text_field.text)

        if not self.input_dialog:
            from kivymd.dialog import MDInputDialog

            self.input_dialog = MDInputDialog(title='Title',
                                              hint_text='Hint text',
                                              size_hint=(.8, .4),
                                              text_button_ok='Ok',
                                              events_callback=result)
        self.input_dialog.open()

    def show_example_alert_dialog(self):
        if not self.alert_dialog:
            from kivymd.dialog import MDDialog

            self.alert_dialog = MDDialog(
                title='Title',
                size_hint=(.8, .4),
                text_button_ok='Ok',
                text="This is Alert dialog",
                events_callback=self.callback_for_menu_items)
        self.alert_dialog.open()

    def show_example_ok_cancel_dialog(self):
        if not self.ok_cancel_dialog:
            from kivymd.dialog import MDDialog

            self.ok_cancel_dialog = MDDialog(
                title='Title',
                size_hint=(.8, .4),
                text_button_ok='Ok',
                text="This is Ok Cancel dialog",
                text_button_cancel='Cancel',
                events_callback=self.callback_for_menu_items)
        self.ok_cancel_dialog.open()

    def show_example_long_dialog(self):
        if not self.long_dialog:
            from kivymd.dialog import MDDialog

            self.long_dialog = MDDialog(
                text="Lorem ipsum dolor sit amet, consectetur adipiscing "
                "elit, sed do eiusmod tempor incididunt ut labore et "
                "dolore magna aliqua. Ut enim ad minim veniam, quis "
                "nostrud exercitation ullamco laboris nisi ut aliquip "
                "ex ea commodo consequat. Duis aute irure dolor in "
                "reprehenderit in voluptate velit esse cillum dolore eu "
                "fugiat nulla pariatur. Excepteur sint occaecat "
                "cupidatat non proident, sunt in culpa qui officia "
                "deserunt mollit anim id est laborum.",
                title='Title',
                size_hint=(.8, .4),
                text_button_ok='Yes',
                events_callback=self.callback_for_menu_items)
        self.long_dialog.open()

    def get_time_picker_data(self, instance, time):
        self.pickers.ids.time_picker_label.text = str(time)
        self.previous_time = time

    def show_example_time_picker(self):
        from kivymd.time_picker import MDTimePicker

        time_dialog = MDTimePicker()
        time_dialog.bind(time=self.get_time_picker_data)

        if self.pickers.ids.time_picker_use_previous_time.active:
            try:
                time_dialog.set_time(self.previous_time)
            except AttributeError:
                pass
        time_dialog.open()

    def set_previous_date(self, date_obj):
        self.previous_date = date_obj
        self.pickers.ids.date_picker_label.text = str(date_obj)

    def show_example_date_picker(self):
        from kivymd.date_picker import MDDatePicker

        if self.pickers.ids.date_picker_use_previous_date.active:
            pd = self.previous_date
            try:
                MDDatePicker(self.set_previous_date, pd.year, pd.month,
                             pd.day).open()
            except AttributeError:
                MDDatePicker(self.set_previous_date).open()
        else:
            MDDatePicker(self.set_previous_date).open()

    def show_example_bottom_sheet(self):
        from kivymd.bottomsheet import MDListBottomSheet

        if not self.bs_menu_1:
            self.bs_menu_1 = MDListBottomSheet()
            self.bs_menu_1.add_item(
                "Here's an item with text only", lambda x: self.
                callback_for_menu_items("Here's an item with text only"))
            self.bs_menu_1.add_item("Here's an item with an icon",
                                    lambda x: self.callback_for_menu_items(
                                        "Here's an item with an icon"),
                                    icon='clipboard-account')
            self.bs_menu_1.add_item(
                "Here's another!",
                lambda x: self.callback_for_menu_items("Here's another!"),
                icon='nfc')
        self.bs_menu_1.open()

    def show_example_grid_bottom_sheet(self):
        if not self.bs_menu_2:
            from kivymd.bottomsheet import MDGridBottomSheet

            self.bs_menu_2 = MDGridBottomSheet()
            self.bs_menu_2.add_item(
                "Facebook",
                lambda x: self.callback_for_menu_items("Facebook"),
                icon_src='./assets/facebook-box.png')
            self.bs_menu_2.add_item(
                "YouTube",
                lambda x: self.callback_for_menu_items("YouTube"),
                icon_src='./assets/youtube-play.png')
            self.bs_menu_2.add_item(
                "Twitter",
                lambda x: self.callback_for_menu_items("Twitter"),
                icon_src='./assets/twitter.png')
            self.bs_menu_2.add_item(
                "Da Cloud",
                lambda x: self.callback_for_menu_items("Da Cloud"),
                icon_src='./assets/cloud-upload.png')
            self.bs_menu_2.add_item(
                "Camera",
                lambda x: self.callback_for_menu_items("Camera"),
                icon_src='./assets/camera.png')
        self.bs_menu_2.open()

    def set_appbar(self):
        from kivymd.toolbar import MDBottomAppBar

        def press_button(inctance):
            toast('Press Button')

        self.md_app_bar = MDBottomAppBar(
            md_bg_color=self.theme_cls.primary_color,
            left_action_items=[['menu', lambda x: x], ['clock', lambda x: x],
                               ['dots-vertical', lambda x: x]],
            anchor='right',
            callback=press_button)

    def move_item_menu(self, anchor):
        md_app_bar = self.md_app_bar
        if md_app_bar.anchor != anchor:
            if len(md_app_bar.right_action_items):
                md_app_bar.left_action_items.append(
                    md_app_bar.right_action_items[0])
                md_app_bar.right_action_items = []
            else:
                left_action_items = md_app_bar.left_action_items
                action_items = left_action_items[0:2]
                md_app_bar.right_action_items = [left_action_items[-1]]
                md_app_bar.left_action_items = action_items

    def set_error_message(self, *args):
        if len(self.root.ids.text_field_error.text) == 2:
            self.root.ids.text_field_error.error = True
        else:
            self.root.ids.text_field_error.error = False

    def add_icon_item(self, name_icon):
        self.main_widget.ids.scr_mngr.get_screen(
            'md icons').ids.rv.data.append({
                'viewclass':
                'MDIconItemForMdIconsList',
                'icon':
                name_icon,
                'text':
                name_icon,
                'callback':
                self.callback_for_menu_items
            })

    def set_list_md_icons(self, text='', search=False):
        self.main_widget.ids.scr_mngr.get_screen('md icons').ids.rv.data = []
        for name_icon in md_icons.keys():
            if search:
                if text in name_icon:
                    self.add_icon_item(name_icon)
            else:
                self.add_icon_item(name_icon)

    def on_pause(self):
        return True

    def on_stop(self):
        pass

    def open_settings(self, *args):
        return False
Пример #60
0
 def on_new_game(self):
     """Handle the new game button"""
     view = ModalView(size_hint=(None, None), size=(300, 300))
     view.add_widget(InfoPanel(callback=self._start_download))
     view.open()