コード例 #1
1
ファイル: gallery_button.py プロジェクト: pilino1234/DAT256
class GalleryButton(MDFloatingActionButton):
    """A FAB which opens the gallery."""

    path_selected_callback = ObjectProperty(lambda: None)

    def __init__(self, **kwargs):
        """Initializes the gallery button"""
        super(GalleryButton, self).__init__(**kwargs)
        self.manager_open = False
        self.manager = None

    def on_release(self):
        """Function called when the button is released."""
        self.file_manager_open()

    def file_manager_open(self):
        """Opens the file manager window"""
        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)

            # Monkey patch file selection so that history is not erased
            def select_dir_or_file(path):
                """Called by tap on the name of the directory or file."""
                if os.path.isfile(path):
                    self.file_manager.select_path(path)
                    return

                self.file_manager.current_path = path
                self.file_manager.show(path)

            self.file_manager.select_dir_or_file = select_dir_or_file

            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.path_selected_callback(path)

        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
コード例 #2
0
class HomeScreen(Screen):
    def workout_options(self):
        layout = BoxLayout(orientation='vertical')

        blank_btn = Button(text='Start Blank',
                           size_hint=[.8, 1],
                           pos_hint={'x': .1},
                           on_release=self.new_workout)
        template_btn = Button(text='Start from Template',
                              size_hint=[.8, 1],
                              pos_hint={'x': .1})
        previous_btn = Button(text='Copy from Previous',
                              size_hint=[.8, 1],
                              pos_hint={'x': .1})

        layout.add_widget(blank_btn)
        layout.add_widget(template_btn)
        layout.add_widget(previous_btn)

        self.popup = ModalView(content=layout,
                               size_hint=[1, .5],
                               pos_hint={'top': .5})
        self.popup.add_widget(layout)

        self.popup.open()

    def new_workout(self, instance):
        self.popup.dismiss()
        self.manager.current = 'workout'
コード例 #3
0
 def my_callback2(instance):
     """
     Функция  для определения поведения всплывающего окна при его закрытии.
     """
     view = ModalView()
     view.dismiss(force=True)
     self.logic()
     return False
コード例 #4
0
class UploadMainWidget(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.files = []
        self.files_boxs = []
        self.uploading = False

    def upload_files(self):
        if len(self.files) > 0:
            for pos, file in enumerate(self.files):
                self.files[pos] = {f"name": file, "status": "None"}
            self.service = App.get_running_app().root.drive
            self.drive = DriveManager(self.service, files=self.files)
            self.drive.func = "upload"
            self.drive.start()
            self.vrf = Clock.schedule_interval(self.check_upload, .1)
        else:
            modal = ModalView(size_hint=(None, None), width=300, height=50)
            modal.add_widget(Label(text="Seleciione arqivos para upload"))
            modal.open()

    def check_upload(self, event):

        for pos, file in enumerate(self.drive.files):
            self.files_boxs[pos].ids.status.text = file["status"]
        if not self.drive.proccessing:
            self.files = []
            self.files_boxs = []
            self.vrf.cancel()

    def openfilechooser(self):
        self.modal = ModalView(size_hint=(.8, .8))
        self.modal.padding = 5

        self.file_widget = BoxLayout(size_hint=(.8, .9))
        self.file_widget.orientation = "vertical"
        self.filec = FileChooserView()
        self.file_widget.add_widget(self.filec)

        self.modal.add_widget(self.file_widget)

        self.boxbtn = BoxLayout(size_hint=(.8, .1))
        self.addbtn = Button(text="Adicionar")
        self.addbtn.on_press = self.selectfiles

        self.cancelbtn = Button(text="Terminar ou cancelar")
        self.cancelbtn.on_press = self.closefilechooser

        self.boxbtn.add_widget(self.addbtn)
        self.boxbtn.add_widget(self.cancelbtn)
        self.file_widget.add_widget(self.boxbtn)
        self.modal.open()

    def closefilechooser(self):
        self.modal.dismiss()

    def selectfiles(self):
        self.filec.on_submit()
コード例 #5
0
ファイル: main.py プロジェクト: Pabluu/Conversor
class Main(App):
    theme_cls = ThemeManager()
    theme_cls.primary_palette = 'Red'
    title = "HQ's TO PDF"

    def __init__(self, **kwargs):
        super(Main, self).__init__(**kwargs)
        self.manager_open = False
        self.manager = None

    def build(self):
        return Init()

    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,
                search='all',
                ext=['.*'])
            self.manager.add_widget(self.file_manager)
            self.file_manager.show(HOME)
        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)
        Thread(target=convert.Converter, args=[path]).start()

    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
コード例 #6
0
ファイル: main.py プロジェクト: snaiffer/TreeNote
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()
コード例 #7
0
ファイル: calendar.py プロジェクト: UsAndRufus/LiSE
class CalendarOptionButton(CalendarWidget, Button):
    options = ListProperty()
    modalview = ObjectProperty()
    cols = BoundedNumericProperty(1, min=1)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._make_modalview()
        self._update_modalview()
        self.bind(cols=self._make_modalview)
        self.bind(options=self._update_modalview)
        self.bind(on_release=self.modalview.open)

    def _make_modalview(self, *args):
        if not self.modalview:
            self.modalview = ModalView()
        if self.modalview.children:
            container = self.modalview.children[0]
        else:
            container = GridLayout(cols=self.cols)
            self.modalview.add_widget(container)
        container.size = container.minimum_size
        self._update_modalview()

    def _update_modalview(self, *args):
        if not self.modalview:
            Clock.schedule_once(self.on_options, 0)
            return
        if not self.modalview.children:
            container = GridLayout(cols=self.cols)
            self.modalview.add_widget(container)
        else:
            container = self.modalview.children[0]
        for option in self.options:
            if type(option) is tuple:
                text, value = option
                container.add_widget(Button(
                    size_hint_y=None, height=30,
                    text=text, on_release=partial(self._set_value_and_close, text)))
            else:
                container.add_widget(Button(
                    text=str(option), on_release=partial(
                    self._set_value_and_close, str(option)),
                    size_hint_y=None, height=30))
        container.size = container.minimum_size

    def _set_value_and_close(self, val, *args):
        self.value = val
        self.modalview.dismiss()
コード例 #8
0
ファイル: filemanager.py プロジェクト: surbhicis/KivyMD-1
class KitchenSinkFileManager(Screen):
    manager_open = False

    def file_manager_open(self):
        from kivymd.uix.filemanager import MDFileManager
        from kivymd.uix.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(os.environ["KITCHEN_SINK_ASSETS"])
            self.manager_open = True
            self.manager.open()

        MDDialog(
            title="Kitchen Sink",
            size_hint=(0.8, 0.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;

        """

        from kivymd.toast import toast

        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
コード例 #9
0
ファイル: Menu.py プロジェクト: tmek1244/Ultimate-TicTacToe
class Menu(Screen):
    que = None
    leave = None

    def connect_to_server(self):
        BigBoard.are_we_playing = True
        App.get_running_app().set_state("in_queue")
        self.que = ModalView(size_hint=(.75, .5))
        time_text = Label(text="00 : 00", font_size=50, id="time_text")
        App.get_running_app().clock_timer = Clock.schedule_interval(
            self.timer_for_que, 1.000)
        self.que.bind(on_dismiss=self.leave_queue_on_dismiss)
        self.que.add_widget(time_text)
        self.que.open()
        TicTacToeApp.que_for_game(App.get_running_app())

    @staticmethod
    def cancel_timer_and_set_menu():
        App.get_running_app().clock_timer.cancel()
        App.get_running_app().set_state("in_menu")

    def leave_queue_on_dismiss(self, dt):
        if App.get_running_app().state == "in_queue":
            self.cancel_timer_and_set_menu()
            App.get_running_app().s.stop()

    def leave_queue_on_join(self):
        self.cancel_timer_and_set_menu()
        self.que.dismiss()

    def timer_for_que(self, dt):
        self.que.children[0].text = plus_sec(self.que.children[0].text)

    def back_to_menu(self):
        self.leave = ModalView(size_hint=(.75, .5))
        text = Label(text="Your opponent leave", font_size=50)
        self.leave.bind(on_dismiss=lambda x: go_to_screen(1))
        self.leave.add_widget(text)
        self.leave.open()
        App.get_running_app().man.if_online = 0
        App.get_running_app().man.who_am_I = 0
        App.get_running_app().state = "in_menu"
        App.get_running_app().man.ids.screen_game_online.ids.pasek.reset()
コード例 #10
0
ファイル: main.py プロジェクト: heyrict/Enquete
class MenuScreen(Screen):
    userDataDir = StringProperty()

    def openFileChooser(self):
        self.view = ModalView()
        self.view.add_widget(OpenDialog(size_hint=(1,1),
            load = self.load, cancel = self.cancel))
        self.view.open()

    def load(self, path, filename):
        if len(filename) != 1:
            print("Please select at least one file")
            pu = WarningPopup(warnTxt="Please select at least one file",
                    onok=lambda:1, oncancel=lambda:1)
            pu.open()
            return
        fname, fext = os.path.splitext(filename[0])
        folderString, fname = os.path.split(fname)
        data_filter = pmdf.PMDFParser(filename[0]).parse()

        csvfile = os.path.join(self.userDataDir,fname+".csv")
        if os.path.exists(csvfile):
            with open(csvfile) as f:
                dataframe = list(csv.DictReader(f))
        else:
            dataframe = []

        dataframe.append({})
        for i in data_filter.field_list:
            dataframe[-1][i] = ""

        mainscr = MainScreen(name="main")
        mainscr.csvfile = csvfile
        mainscr.data_filter = data_filter
        mainscr.dataframe = dataframe

        self.view.dismiss()
        self.manager.switch_to(mainscr)

    def cancel(self):
        self.view.dismiss()
コード例 #11
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
コード例 #12
0
class HomeScreen(Screen):
    def workout_options(self):
        layout = BoxLayout(orientation='vertical')

        blank_btn = Button(text='Start Blank', size_hint=[.8, 1],
                pos_hint={'x': .1}, on_release=self.new_workout)
        template_btn = Button(text='Start from Template', size_hint=[.8, 1],
                pos_hint={'x': .1})
        previous_btn = Button(text='Copy from Previous', size_hint=[.8, 1],
                pos_hint={'x': .1})

        layout.add_widget(blank_btn)
        layout.add_widget(template_btn)
        layout.add_widget(previous_btn)

        self.popup = ModalView(content=layout, size_hint=[1, .5],
                pos_hint={'top': .5})
        self.popup.add_widget(layout)

        self.popup.open()

    def new_workout(self, instance):
        self.popup.dismiss()
        self.manager.current = 'workout'
コード例 #13
0
 def on_status(self, instance, new_value):
     status = new_value
     a = sum(status[0:3])
     b = sum(status[3:6])
     c = sum(status[6:9])
     d = sum(status[0::3])
     e = sum(status[1::3])
     f = sum(status[2::3])
     g = sum(status[::4])
     h = sum(status[2:-2:2])
     sums = [a, b, c, d, e, f, g, h]
     if 3 in sums:
         winner = 'O WIN'
     elif -3 in sums:
         winner = 'X'
     elif 0 not in self.status:
         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)
         popup.bind(on_dismiss=self.reset)
         popup.open()
         popup.dismiss()
コード例 #14
0
ファイル: main.py プロジェクト: onecore/rest-viewer-app
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
コード例 #15
0
class Mergency(App, Designer):
    theme_cls = ThemeManager()
    theme_cls.accent_palette = 'Orange'
    previous_date = ObjectProperty()
    title = "Mergency"
    theme_cls.theme_style = 'Dark'

    def __init__(self, **kwargs):
        super().__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_app_bar = None
        self.instance_menu_demo_apps = 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.my_snackbar = None
        self._interval = 0
        self.tick = 0
        self.create_stack_floating_buttons = False
        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))
        # DB Data =======================================================
        self.db = None
        self.host = StringProperty(None)
        self.user = StringProperty(None)
        self.password = StringProperty(None)
        self.service = StringProperty(None)
        self.port = StringProperty(None)
        # TABS Data =====================================================
        self.accidents = None
        self.hospitals = None
        self.ambulances = None
        self.doctors = None
        self.patients = None

    def crop_image_for_tile(self, instance, size, path_to_crop_image):
        """Crop images for Grid screen."""

        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.pickers 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):
        """Adds MDCardPost objects to the screen Cards
        when the screen is open."""

        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="H5",
                    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):
        """Set new label on the screen UpdateSpinner."""
        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 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 show_user_example_animation_card(self):
        """Create and open instance MDUserAnimationCard
        for the screen UserCard."""

        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):
        """Create and show instance Snackbar for the screen MySnackBar."""
        def callback(instance):
            toast(instance.text)

        def wait_interval(interval):
            self._interval += interval
            if self._interval > self.my_snackbar.duration:
                anim = Animation(y=dp(10), d=.2)
                anim.start(self.snackbar.ids.button)
                Clock.unschedule(wait_interval)
                self._interval = 0
                self.my_snackbar = None

        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=callback).show()
        elif snack_type == 'verylong':
            Snackbar(text="This is a very very very very very very very "
                     "long snackbar!").show()
        elif snack_type == 'float':
            if not self.my_snackbar:
                self.my_snackbar = Snackbar(text="This is a snackbar!",
                                            button_text='Button',
                                            duration=3,
                                            button_callback=callback)
                self.my_snackbar.show()
                anim = Animation(y=dp(72), d=.2)
                anim.bind(on_complete=lambda *args: Clock.schedule_interval(
                    wait_interval, 0))
                anim.start(self.snackbar.ids.button)

    def show_example_input_dialog(self):
        """Creates an instance of the dialog box and displays it
        on the screen for the screen Dialogs."""
        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_date(self, instance, time):
        """Get date for MDTimePicker from the screen Pickers."""

        self.pickers.ids.time_picker_label.text = str(time)
        self.previous_time = time

    def show_example_time_picker(self):
        """Show MDTimePicker from the screen Pickers."""

        from kivymd.pickers import MDTimePicker

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

        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):
        """Set previous date for MDDatePicker from the screen Pickers."""

        self.previous_date = date_obj
        self.pickers.ids.date_picker_label.text = str(date_obj)

    def show_example_date_picker(self):
        """Show MDDatePicker from the screen Pickers."""

        from kivymd.pickers 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):
        """Show menu from the screen BottomSheet."""

        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):
        """Show menu from the screen BottomSheet."""

        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_title_toolbar(self, title):
        """Set string title in MDToolbar for the whole application."""

        self.main_widget.ids.toolbar.title = title

    def set_appbar(self):
        """Create MDBottomAppBar for the screen BottomAppBar."""

        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):
        """Sets icons in MDBottomAppBar for the screen BottomAppBar."""

        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):
        """Checks text of TextField with type "on_error"
        for the screen TextFields."""

        text_field_error = args[0]
        if len(text_field_error.text) == 2:
            text_field_error.error = True
        else:
            text_field_error.error = False

    def set_list_md_icons(self, text='', search=False):
        """Builds a list of icons for the screen MDIcons."""
        def add_icon_item(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
                })

        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:
                    add_icon_item(name_icon)
            else:
                add_icon_item(name_icon)

    def set_menu_for_demo_apps(self):
        if not len(self.menu_for_demo_apps):
            for name_item in self.demo_apps_list:
                self.menu_for_demo_apps.append({
                    'viewclass':
                    'OneLineListItem',
                    'text':
                    name_item,
                    'on_release':
                    lambda x=name_item: self.show_demo_apps(x)
                })

    def show_demo_apps(self, name_item):
        name_item = name_item.lower()
        {
            'coffee menu': self.show_coffee_menu,
            'shop window': self.show_shop_window,
            'registration': self.show_registration_form_one,
            'fitness club': self.show_fitness_club
        }[name_item]()
        self.main_widget.ids.scr_mngr.current = name_item
        self.instance_menu_demo_apps.dismiss()

    # CUSTOM ========================================================================
    def button_connect(self, host, service, port, user, password):
        self.db = Database(host, service, port, user, password)
        self.db.connect()
        return

    def button_disconnect(self):
        if (self.db != None):
            self.db.disconnect()
            self.db = None
        else:
            pass
        return

    def dummy_push(self):
        if (self.db != None):
            self.db.init_tables(DB_SCHEMA)
            self.db.dummy_insert()
            self.db.dummy_select()
        else:
            pass
        return

    def dummy_pop(self):
        if (self.db != None):
            self.db.rollback_tables(DB_SCHEMA)
        else:
            pass
        return

    def remove_cards(self, tab):
        if (len(tab.children) != 0):
            tab.clear_widgets()
        else:
            pass
        return

    # IMPORTANT
    # Need to separate these methods into update and refresh for correct
    # content management, at this moment everytime a tab is accesed it
    # just adds again the content of the DB table over the old one!
    # FIX ASAP!
    def get_accidents(self, instance_grid_card):
        print(
            "ACCIDENTS --------------------------------------------------------------"
        )
        """Adds MDCardPost objects to the screen Cards
        when the screen is open."""

        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])

        menu_items = [{
            'viewclass': 'MDMenuItem',
            'text': 'Remove',
            'callback': self.callback_for_menu_items
        } for _ in range(1)]
        # Implement a method to check empty tables and change above!
        if (self.db != None):
            try:
                self.accidents = self.db.get_info("Accident", "*")
            except Exception as ex:
                print(ex)
                return
            for _ in range(len(self.accidents)):
                instance_grid_card.add_widget(
                    MDCardPost(
                        right_menu=menu_items,
                        swipe=True,
                        name_data=
                        f"County: {self.accidents[_][1]}\nID:    {self.accidents[_][0]}\nAdress: {self.accidents[_][2]}\nDetails: {self.accidents[_][3]}",
                        tile_font_style='H4',
                        path_to_avatar="assets/m_tab_accidents.png",
                        card_size=(Window.width, Window.height - 480),
                        text_post="",
                        callback=callback))
        else:
            pass  # Implement to add here a Label to say that the DB table is empty
        return

    def get_hospitals(self, instance_grid_card):
        print(
            "HOSPITALS --------------------------------------------------------------"
        )
        """Adds MDCardPost objects to the screen Cards
        when the screen is open."""

        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])

        menu_items = [{
            'viewclass': 'MDMenuItem',
            'text': 'Remove',
            'callback': self.callback_for_menu_items
        } for _ in range(1)]
        # Implement a method to check empty tables and change above!
        if (self.db != None):
            try:
                self.hospitals = self.db.get_info("Hospital", "*")
            except Exception as ex:
                print(ex)
                return
            for _ in range(len(self.hospitals)):
                instance_grid_card.add_widget(
                    MDCardPost(
                        right_menu=menu_items,
                        swipe=True,
                        name_data=
                        f"{self.hospitals[_][1]}\nID:    {self.hospitals[_][0]}\nAdress: {self.hospitals[_][2]}\n",
                        tile_font_style='H4',
                        path_to_avatar="assets/m_tab_hospitals.png",
                        card_size=(Window.width, Window.height - 480),
                        text_post="",
                        callback=callback))
        else:
            pass  # Implement to add here a Label to say that the DB table is empty
        return

    def get_ambulances(self, instance_grid_card):
        print(
            "AMBULANCES -------------------------------------------------------------"
        )
        """Adds MDCardPost objects to the screen Cards
        when the screen is open."""

        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])

        menu_items = [{
            'viewclass': 'MDMenuItem',
            'text': 'Remove',
            'callback': self.callback_for_menu_items
        } for _ in range(1)]
        # Implement a method to check empty tables and change above!
        if (self.db != None):
            try:
                self.ambulances = self.db.get_info("Ambulance", "*")
            except Exception as ex:
                print(ex)
                return
            for _ in range(len(self.ambulances)):
                # 706F6F
                # FFAA00
                if (self.ambulances[_][4] == 0):
                    s = "assets/m_tab_ambulances_0.png"
                elif (self.ambulances[_][4] == 1):
                    s = "assets/m_tab_ambulances_1.png"
                else:
                    s = "assets/m_tab_ambulances_1.png"
                instance_grid_card.add_widget(
                    MDCardPost(
                        right_menu=menu_items,
                        swipe=True,
                        name_data=
                        f"{self.ambulances[_][2]}\nID:    {self.ambulances[_][0]}",
                        tile_font_style='H4',
                        path_to_avatar=s,
                        card_size=(Window.width, Window.height - 480),
                        text_post=
                        f"Producer:          {self.ambulances[_][1]}\nCapacity:     {self.ambulances[_][3]} persons",
                        callback=callback))
        else:
            pass  # Implement to add here a Label to say that the DB table is empty
        return

    def get_doctors(self, instance_grid_card):
        print(
            "DOCTORS ----------------------------------------------------------------"
        )
        """Adds MDCardPost objects to the screen Cards
        when the screen is open."""

        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])

        menu_items = [{
            'viewclass': 'MDMenuItem',
            'text': 'Remove',
            'callback': self.callback_for_menu_items
        } for _ in range(1)]
        # Implement a method to check empty tables and change above!
        if (self.db != None):
            try:
                self.doctors = self.db.get_info("Doctor", "*")
            except Exception as ex:
                print(ex)
                return
            for _ in range(len(self.doctors)):
                if (self.doctors[_][3] == "M"):
                    s = "assets/m_tab_doctors_m.png"
                elif (self.doctors[_][3] == "F"):
                    s = "assets/m_tab_doctors_f.png"
                else:
                    s = "assets/m_tab_doctors_m.png"
                instance_grid_card.add_widget(
                    MDCardPost(
                        right_menu=menu_items,
                        swipe=True,
                        name_data=
                        f"{self.doctors[_][2]} {self.doctors[_][1]} ({self.doctors[_][3]})\nID:    {self.doctors[_][0]}",
                        tile_font_style='H4',
                        path_to_avatar=s,
                        card_size=(Window.width, Window.height - 480),
                        text_post=f"Birthday:          {self.doctors[_][4]}",
                        callback=callback))
        else:
            pass  # Implement to add here a Label to say that the DB table is empty
        return

    def get_patients(self, instance_grid_card):
        print(
            "PATIENTS ---------------------------------------------------------------"
        )
        """Adds MDCardPost objects to the screen Cards
        when the screen is open."""

        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])

        menu_items = [{
            'viewclass': 'MDMenuItem',
            'text': 'Remove',
            'callback': self.callback_for_menu_items
        } for _ in range(1)]
        # Implement a method to check empty tables and change above!
        if (self.db != None):
            try:
                self.patients = self.db.get_info("Patient", "*")
            except Exception as ex:
                print(ex)
                return
            for _ in range(len(self.patients)):
                if (self.patients[_][3] == "M"):
                    s = "assets/m_tab_pacients_m.png"
                elif (self.patients[_][3] == "F"):
                    s = "assets/m_tab_pacients_f.png"
                else:
                    s = "assets/m_tab_pacients_m.png"
                instance_grid_card.add_widget(
                    MDCardPost(
                        right_menu=menu_items,
                        swipe=True,
                        name_data=
                        f"{self.patients[_][2]} {self.patients[_][1]} ({self.patients[_][3]})\nID:    {self.patients[_][0]}",
                        tile_font_style='H4',
                        path_to_avatar=s,
                        card_size=(Window.width, Window.height - 480),
                        text_post=
                        f"Birthday:          {self.patients[_][4]}\nBlood Type:     {self.patients[_][5]}\nRH:                      {self.patients[_][6]}",
                        callback=callback))
        else:
            pass  # Implement to add here a Label to say that the DB table is empty
        return

    # CUSTOM ========================================================================

    def build(self):
        self.main_widget = Builder.load_file(
            os.path.join(os.path.dirname(__file__), "./Mergency.kv"))
        return self.main_widget

    def on_pause(self):
        return True

    def on_stop(self):
        pass

    def open_settings(self, *args):
        return False
コード例 #16
0
class MainApp(MDApp):
    gridi = None

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

        Window.bind(on_keyboard=self.events)
        self.manager_open = False
        self.file_manager = MDFileManager(
            exit_manager=self.exit_manager,
            select_path=self.select_path,
            previous=True,
        )

    def build(self):

        self.saturday = DaiBox()
        self.sunday = DaiBox()
        self.monday = DaiBox()
        self.tuesday = DaiBox()
        self.wednesday = DaiBox()
        self.thursday = DaiBox()
        self.friday = DaiBox()
        self.day = {
            'Saturday': self.saturday,
            'Sunday': self.sunday,
            'Monday': self.monday,
            'Tuesday': self.tuesday,
            'Wednesday': self.wednesday,
            'Thursday': self.thursday,
            'Friday': self.friday,
        }
        self.main_screen = Main_screen()
        self.s = self.main_screen.ids.scroll
        self.b = self.main_screen.ids.sale_box
        self.pro = self.main_screen.ids.profile
        self.pro_scr = self.pro.ids.pro_scr
        self.pro_scr.current = "review"
        self.category = self.b.ids.category
        self.titl = self.b.ids.title
        self.desc = self.b.ids.description
        self.amnt = self.b.ids.amount
        self.price = self.b.ids.price

        return self.main_screen

    def s_pop(self, *args):
        self.s_pop = S_popup()
        self.s_pop.open()

    def close_spopup(self, *args):
        self.s_pop.dismiss()

    def bottom_sheet(self, *args):
        self.b_menu = MDListBottomSheet(radius=15, radius_from="top")
        self.b_menu.add_item(text="Change Profile Photo",
                             callback=self.pro_photo)
        self.b_menu.add_item(text="Change Cover Photo",
                             callback=self.pro_photo)
        self.b_menu.open()

    def pro_photo(self, *args):
        print("Okk")

    def dailouge(self, id, *args):
        self.recent_day = self.day[id.text]
        self.modal = ModalView(size_hint=(0.95, 0.5), auto_dismiss=False)
        self.modal.add_widget(self.recent_day)
        self.modal.open()

    def dai_ok(self):
        self.modal.dismiss()
        Clock.schedule_once(self.daii_ok, 0.2)

    def daii_ok(self, *args):
        self.modal.clear_widgets()
        del self.modal

    def submit(self, *args):
        self.sat = [
            self.saturday.ids.a.active, self.saturday.ids.b.active,
            self.saturday.ids.c.active, self.saturday.ids.d.active,
            self.saturday.ids.e.active
        ]
        self.sun = [
            self.sunday.ids.a.active, self.sunday.ids.b.active,
            self.sunday.ids.c.active, self.sunday.ids.d.active,
            self.sunday.ids.e.active
        ]
        self.mon = [
            self.monday.ids.a.active, self.monday.ids.b.active,
            self.monday.ids.c.active, self.monday.ids.d.active,
            self.monday.ids.e.active
        ]
        self.tue = [
            self.tuesday.ids.a.active, self.tuesday.ids.b.active,
            self.tuesday.ids.c.active, self.tuesday.ids.d.active,
            self.tuesday.ids.e.active
        ]
        self.wed = [
            self.wednesday.ids.a.active, self.wednesday.ids.b.active,
            self.wednesday.ids.c.active, self.wednesday.ids.d.active,
            self.wednesday.ids.e.active
        ]
        self.thu = [
            self.thursday.ids.a.active, self.thursday.ids.b.active,
            self.thursday.ids.c.active, self.thursday.ids.d.active,
            self.thursday.ids.e.active
        ]
        self.fri = [
            self.friday.ids.a.active, self.friday.ids.b.active,
            self.friday.ids.c.active, self.friday.ids.d.active,
            self.friday.ids.e.active
        ]
        self.sat = [str(i) for i in self.sat]
        self.sun = [str(i) for i in self.sun]
        self.mon = [str(i) for i in self.mon]
        self.tue = [str(i) for i in self.tue]
        self.wed = [str(i) for i in self.wed]
        self.thu = [str(i) for i in self.thu]
        self.fri = [str(i) for i in self.fri]
        self.result = {}
        self.result["category"] = self.category.text
        self.result["title"] = self.titl.text
        self.result["description"] = self.desc.text
        self.result["amount"] = self.amnt.text
        self.result["Saturday"] = self.sat
        self.result["Sunday"] = self.sun
        self.result["Monday"] = self.mon
        self.result["Tuesday"] = self.tue
        self.result["Wednesday"] = self.wed
        self.result["Thursday"] = self.thu
        self.result["Friday"] = self.fri
        print(self.result)

    def file_manager_open(self):
        if self.gridi == None:
            self.file_manager.show('/storage/emulated/0/')
            self.manager_open = True
        else:
            toast("Only 1 Photo!")

    def select_path(self, path):
        if self.gridi == None:
            self.path = str(path)
            self.gridi = self.b.ids.grid_img
            self.grdimg = GridImage()
            self.img = self.grdimg.ids.img
            self.img.source = self.path
            self.gridi.add_widget(self.grdimg)
            self.exit_manager()
            toast(path)
        else:
            self.exit_manager()
            toast("Only 1 Photo!")

    def close_image(self, *args):
        self.gridi.remove_widget(self.grdimg)
        del self.grdimg
        del self.img
        self.gridi = None

    def exit_manager(self, *args):

        self.manager_open = False
        self.file_manager.close()

    def events(self, instance, keyboard, keycode, text, modifiers):

        if keyboard in (1001, 27):
            if self.manager_open:
                self.file_manager.back()
        return True
コード例 #17
0
ファイル: main.py プロジェクト: salhi100/KivyMD
class KitchenSink(App, Screens):
    theme_cls = ThemeManager()
    theme_cls.primary_palette = "BlueGray"
    theme_cls.accent_palette = "Gray"
    previous_date = ObjectProperty()
    title = "Kitchen Sink"

    def __init__(self, **kwargs):
        super().__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

        # Default class instances.
        self.manager = None
        self.md_app_bar = None
        self.instance_menu_demo_apps = None
        self.instance_menu_source_code = 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.user_card = None
        self.bs_menu_1 = None
        self.bs_menu_2 = None
        self.popup_screen = None
        self.my_snackbar = None
        self.dialog_load_kv_files = None

        self.create_stack_floating_buttons = False
        self.manager_open = False
        self.cards_created = False

        self._interval = 0
        self.tick = 0
        self.x = 0
        self.y = 25
        self.file_source_code = ""

        self.hex_primary_color = get_hex_from_color(
            self.theme_cls.primary_color)
        self.previous_text = (
            f"Welcome to the application [b][color={self.hex_primary_color}]"
            f"Kitchen Sink[/color][/b].\nTo see [b]"
            f"[color={self.hex_primary_color}]KivyMD[/color][/b] "
            f"examples, open the menu and select from the list the desired "
            f"example or")
        self.previous_text_end = (
            f"for show example apps\n\n"
            f"Author - [b][color={self.hex_primary_color}]"
            f"Andrés Rodríguez[/color][/b]\n"
            f"[u][b][color={self.hex_primary_color}]"
            f"[email protected][/color][/b][/u]\n\n\n"
            f"Authors this Fork:\n\n"
            f"[b][color={self.hex_primary_color}]"
            f"Ivanov Yuri[/color][/b]\n"
            f"[u][b][color={self.hex_primary_color}]"
            f"[email protected][/color][/b][/u]\n\n"
            f"[b][color={self.hex_primary_color}]Artem S. Bulgakov[/color][/b]\n"
            f"[u][b][color={self.hex_primary_color}]"
            f"[email protected][/color][/b][/u]\n\n"
            f"and contributors...")
        self.names_contacts = (
            "Alexandr Taylor",
            "Yuri Ivanov",
            "Robert Patric",
            "Bob Marley",
            "Magnus Carlsen",
            "Jon Romero",
            "Anna Bell",
            "Maxim Kramerer",
            "Sasha Gray",
            "Vladimir Ivanenko",
        )
        self.demo_apps_list = [
            "Shop Window",
            "Coffee Menu",
            "Fitness Club",
            "Registration",
            "Account Page",
        ]
        self.list_name_icons = list(md_icons.keys())[0:15]
        Window.bind(on_keyboard=self.events)
        crop_image(
            (Window.width, int(dp(Window.height * 35 // 100))),
            f"{demos_assets_path}guitar-1139397_1280.png",
            f"{demos_assets_path}guitar-1139397_1280_crop.png",
        )

    def set_list_for_refresh_layout(self):
        async def set_list_for_refresh_layout():
            names_icons_list = list(md_icons.keys())[self.x:self.y]
            for name_icon in names_icons_list:
                await asynckivy.sleep(0)
                self.data["Refresh Layout"]["object"].ids.box.add_widget(
                    ItemForListRefreshLayout(icon=name_icon, text=name_icon))
            self.data["Refresh Layout"][
                "object"].ids.refresh_layout.refresh_done()

        asynckivy.start(set_list_for_refresh_layout())

    def refresh_callback(self, *args):
        """A method that updates the state of your application
        while the spinner remains on the screen."""
        def refresh_callback(interval):
            self.data["Refresh Layout"]["object"].ids.box.clear_widgets()
            if self.x == 0:
                self.x, self.y = 25, 50
            else:
                self.x, self.y = 0, 25
            self.set_list_for_refresh_layout()
            self.tick = 0

        Clock.schedule_once(refresh_callback, 1)

    def build_tabs(self):
        for name_tab in self.list_name_icons:
            tab = Factory.MyTab(text=name_tab)
            self.data["Tabs"]["object"].ids.android_tabs.add_widget(tab)

    def switch_tabs_to_icon(self, istance_android_tabs):
        for i, instance_tab in enumerate(
                istance_android_tabs.ids.scrollview.children[0].children):
            istance_android_tabs.ids.scrollview.children[0].remove_widget(
                instance_tab)
            istance_android_tabs.add_widget(
                Factory.MyTab(text=self.list_name_icons[i]))

    def switch_tabs_to_text(self, istance_android_tabs):
        for instance_tab in istance_android_tabs.ids.scrollview.children[
                0].children:
            for k, v in md_icons.items():
                if v == instance_tab.text:
                    istance_android_tabs.ids.scrollview.children[
                        0].remove_widget(instance_tab)
                    istance_android_tabs.add_widget(
                        Factory.MyTab(
                            text=" ".join(k.split("-")).capitalize()))
                    break

    def crop_image_for_tile(self, instance, size, path_to_crop_image):
        """Crop images for Grid screen."""

        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.uix.picker import MDThemePicker

            self.md_theme_picker = MDThemePicker()
        self.md_theme_picker.open()

    def example_add_stack_floating_buttons(self):
        from kivymd.uix.stackfloatingbutton 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_expansion_panel(self):
        from kivymd.uix.expansionpanel import MDExpansionPanel

        def callback(text):
            toast(f"{text} to {content.name_item}")

        content = ContentForAnimCard(callback=callback)

        for name_contact in self.names_contacts:
            self.data["Expansion Panel"]["object"].ids.anim_list.add_widget(
                MDExpansionPanel(
                    content=content,
                    icon="assets/kivy-logo-white-512.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.uix.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.data["Download File"]["object"].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.uix.filemanager import MDFileManager
        from kivymd.uix.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=(0.8, 0.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):
        """Adds MDCardPost objects to the screen Cards
        when the screen is open."""

        from kivymd.uix.card 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.",
                ))

            image_for_card = (
                f"{demos_assets_path}kitten-for_card-1049129_1280-crop.png")
            if not os.path.exists(image_for_card):
                crop_image(
                    (int(Window.width), int(dp(200))),
                    f"{demos_assets_path}kitten-1049129_1280.png",
                    image_for_card,
                )
            instance_grid_card.add_widget(
                MDCardPost(
                    source=image_for_card,
                    tile_text="Little Baby",
                    tile_font_style="H5",
                    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):
        """Set new label on the screen UpdateSpinner."""
        def update_screen(interval):
            self.tick += 1
            if self.tick > 2:
                instance.update = True
                self.tick = 0
                self.data["Update Screen Widget"][
                    "object"].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)
        return self.main_widget

    def show_popup_screen(self):
        if not self.popup_screen:
            self.popup_screen = self.data["Popup Screen"]["object"].ids.popup
            content_screen = ContentForPopupScreen()
            self.popup_screen.screen = content_screen
            self.popup_screen.padding = dp(10)
            self.popup_screen.background_color = self.theme_cls.primary_color
        self.popup_screen.show()

    def show_user_example_animation_card(self):
        """Create and open instance MDUserAnimationCard
        for the screen UserCard."""

        from kivymd.uix.useranimationcard import MDUserAnimationCard

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

        if not self.user_card:
            image_for_user_card = (
                f"{demos_assets_path}guitar-for-user-card1139397_1280-crop.png"
            )
            if not os.path.exists(image_for_user_card):
                crop_image(
                    (int(Window.width), int(dp(Window.height * 40 // 100))),
                    f"{demos_assets_path}guitar-1139397_1280.png",
                    image_for_user_card,
                )

            self.user_card = MDUserAnimationCard(
                user_name="Lion Lion",
                path_to_avatar=image_for_user_card,
                callback=main_back_callback,
            )
            self.user_card.box_content.add_widget(ContentForAnimCard())
        self.user_card.open()

    def show_example_snackbar(self, snack_type):
        """Create and show instance Snackbar for the screen MySnackBar."""
        def callback(instance):
            toast(instance.text)

        def wait_interval(interval):
            self._interval += interval
            if self._interval > self.my_snackbar.duration:
                anim = Animation(y=dp(10), d=0.2)
                anim.start(self.data["Snackbars"]["object"].ids.button)
                Clock.unschedule(wait_interval)
                self._interval = 0
                self.my_snackbar = None

        from kivymd.uix.snackbar 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=callback,
            ).show()
        elif snack_type == "verylong":
            Snackbar(text="This is a very very very very very very very "
                     "long snackbar!").show()
        elif snack_type == "float":
            if not self.my_snackbar:
                self.my_snackbar = Snackbar(
                    text="This is a snackbar!",
                    button_text="Button",
                    duration=3,
                    button_callback=callback,
                )
                self.my_snackbar.show()
                anim = Animation(y=dp(72), d=0.2)
                anim.bind(on_complete=lambda *args: Clock.schedule_interval(
                    wait_interval, 0))
                anim.start(self.data["Snackbars"]["object"].ids.button)

    def show_example_input_dialog(self):
        """Creates an instance of the dialog box and displays it
        on the screen for the screen Dialogs."""
        def result(text_button, instance):
            toast(instance.text_field.text)

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

            self.input_dialog = MDInputDialog(
                title="Title",
                hint_text="Hint text",
                size_hint=(0.8, 0.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.uix.dialog import MDDialog

            self.alert_dialog = MDDialog(
                title="Title",
                size_hint=(0.8, 0.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.uix.dialog import MDDialog

            self.ok_cancel_dialog = MDDialog(
                title="Title",
                size_hint=(0.8, 0.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.uix.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=(0.8, 0.4),
                text_button_ok="Yes",
                events_callback=self.callback_for_menu_items,
            )
        self.long_dialog.open()

    def get_time_picker_date(self, time):
        """Get date for MDTimePicker from the screen Pickers."""

        self.data["Pickers"]["object"].ids.time_picker_label.text = str(time)
        self.previous_time = time

    def show_example_time_picker(self):
        """Show MDTimePicker from the screen Pickers."""

        from kivymd.uix.picker import MDTimePicker

        time_dialog = MDTimePicker(self.get_time_picker_date)

        if self.data["Pickers"][
                "object"].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):
        """Set previous date for MDDatePicker from the screen Pickers."""

        self.previous_date = date_obj
        self.data["Pickers"]["object"].ids.date_picker_label.text = str(
            date_obj)

    def show_example_date_picker(self):
        """Show MDDatePicker from the screen Pickers."""

        from kivymd.uix.picker import MDDatePicker

        if self.data["Pickers"][
                "object"].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):
        """Show menu from the screen BottomSheet."""

        from kivymd.uix.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):
        """Show menu from the screen BottomSheet."""

        if not self.bs_menu_2:
            from kivymd.uix.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_title_toolbar(self, title):
        """Set string title in MDToolbar for the whole application."""

        self.main_widget.ids.toolbar.title = title

    def set_appbar(self):
        """Create MDBottomAppBar for the screen BottomAppBar."""

        from kivymd.uix.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):
        """Sets icons in MDBottomAppBar for the screen BottomAppBar."""

        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 show_password(self, field, button):
        """
        Called when you press the right button in the password field
        for the screen TextFields.

        instance_field: kivy.uix.textinput.TextInput;
        instance_button: kivymd.button.MDIconButton;

        """

        # Show or hide text of password, set focus field
        # and set icon of right button.
        field.password = not field.password
        field.focus = True
        button.icon = "eye" if button.icon == "eye-off" else "eye-off"

    def set_error_message(self, *args):
        """Checks text of TextField with type "on_error"
        for the screen TextFields."""

        text_field_error = args[0]
        if len(text_field_error.text) == 2:
            text_field_error.error = True
        else:
            text_field_error.error = False

    def set_list_md_icons(self, text="", search=False):
        """Builds a list of icons for the screen MDIcons."""
        def add_icon_item(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,
                })

        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:
                    add_icon_item(name_icon)
            else:
                add_icon_item(name_icon)

    def set_source_code_file(self):
        """Assigns the file_source_code attribute the file name
        with example code for the current screen."""

        if self.main_widget.ids.scr_mngr.current == "code viewer":
            return

        has_screen = False
        for name_item_drawer in self.data.keys():
            if (self.data[name_item_drawer]["name_screen"] ==
                    self.main_widget.ids.scr_mngr.current):
                self.file_source_code = self.data[name_item_drawer].get(
                    "source_code", None)
                has_screen = True
                break
        if not has_screen:
            self.file_source_code = None

    def open_context_menu_source_code(self, instance):
        def callback_context_menu(icon):
            context_menu.dismiss()

            if not self.file_source_code:
                from kivymd.uix.snackbar import Snackbar

                Snackbar(text="No source code for this example").show()
                return
            if icon == "source-repository":
                if platform in ("win", "linux", "macosx"):
                    webbrowser.open(
                        f"https://github.com/HeaTTheatR/KivyMD/wiki/"
                        f"{os.path.splitext(self.file_source_code)[0]}")
                return
            elif icon == "language-python":
                self.main_widget.ids.scr_mngr.current = "code viewer"
                if self.file_source_code:
                    with open(
                            f"{self.directory}/KivyMD.wiki/{self.file_source_code}"
                    ) as source_code:
                        self.data["Source code"][
                            "object"].ids.code_input.text = source_code.read()

        menu_for_context_menu_source_code = []
        data = {
            "Source code": "language-python",
            "Open in Wiki": "source-repository",
        }
        if self.main_widget.ids.scr_mngr.current == "code viewer":
            data = {"Open in Wiki": "source-repository"}
        for name_item in data.keys():
            menu_for_context_menu_source_code.append({
                "viewclass":
                "MDIconItemForMdIconsList",
                "text":
                name_item,
                "icon":
                data[name_item],
                "text_color": [1, 1, 1, 1],
                "callback":
                lambda x=name_item: callback_context_menu(x),
            })
        context_menu = MDDropdownMenu(
            items=menu_for_context_menu_source_code,
            max_height=dp(260),
            width_mult=3,
        )
        context_menu.open(instance.ids.right_actions.children[0])

    def open_menu_for_demo_apps(self, instance):
        """
        Called when you click the "Click me" button on the start screen.
        Creates and opens a list of demo applications.

        :type instance: <kivymd.uix.button.MDRaisedButton object>

        """

        if not self.instance_menu_demo_apps:
            menu_for_demo_apps = []
            for name_item in self.demo_apps_list:
                menu_for_demo_apps.append({
                    "viewclass":
                    "OneLineListItem",
                    "text":
                    name_item,
                    "on_release":
                    lambda x=name_item: self.show_demo_apps(x),
                })
            self.instance_menu_demo_apps = MDDropdownMenu(
                items=menu_for_demo_apps,
                max_height=dp(260),
                width_mult=4,
                _center=True,
            )
        self.instance_menu_demo_apps.open(instance)

    def show_demo_apps(self, name_item):
        self.show_screens_demo(name_item)
        self.main_widget.ids.scr_mngr.current = name_item.lower()
        self.instance_menu_demo_apps.dismiss()

    def on_pause(self):
        return True

    def on_start(self):
        def _load_kv_for_demo(name_screen):
            from demo_apps.formone import FormOne
            from demo_apps.shopwindow import ShopWindow
            from demo_apps.coffeemenu import CoffeeMenu
            from demo_apps.fitnessclub import FitnessClub
            from demo_apps.accountpage import AccountPage

            Builder.load_string(self.data_for_demo[name_screen]["kv_string"])
            self.data_for_demo[name_screen]["object"] = eval(
                self.data_for_demo[name_screen]["class"])
            self.main_widget.ids.scr_mngr.add_widget(
                self.data_for_demo[name_screen]["object"])

        async def load_all_kv_files():
            for name_screen in self.data.keys():
                await asynckivy.sleep(0)
                self.dialog_load_kv_files.name_kv_file = name_screen
                Builder.load_string(self.data[name_screen]["kv_string"])
                self.data[name_screen]["object"] = eval(
                    self.data[name_screen]["Factory"])
                if name_screen == "Bottom App Bar":
                    self.set_appbar()
                    self.data[name_screen]["object"].add_widget(
                        self.md_app_bar)
                self.main_widget.ids.scr_mngr.add_widget(
                    self.data[name_screen]["object"])
                if name_screen == "Text fields":
                    self.data[name_screen]["object"].ids.text_field_error.bind(
                        on_text_validate=self.set_error_message,
                        on_focus=self.set_error_message,
                    )
                elif name_screen == "MD Icons":
                    self.set_list_md_icons()
                elif name_screen == "Tabs":
                    self.build_tabs()
                elif name_screen == "Refresh Layout":
                    self.set_list_for_refresh_layout()

            from demo_apps.formone import registration_form_one
            from demo_apps.shopwindow import screen_shop_window
            from demo_apps.coffeemenu import screen_coffee_menu
            from demo_apps.fitnessclub import screen_fitness_club
            from demo_apps.accountpage import screen_account_page

            data = {
                "Registration": registration_form_one,
                "Shop Window": screen_shop_window,
                "Coffee Menu": screen_coffee_menu,
                "Fitness Club": screen_fitness_club,
                "Account Page": screen_account_page,
            }

            for name_screen in data.keys():
                await asynckivy.sleep(0)
                self.dialog_load_kv_files.name_kv_file = name_screen
                self.data_for_demo[name_screen]["kv_string"] = data[
                    name_screen]
                _load_kv_for_demo(name_screen)

            self.dialog_load_kv_files.dismiss()

        self.dialog_load_kv_files = DialogLoadKvFiles()
        self.dialog_load_kv_files.open()
        asynckivy.start(load_all_kv_files())

    def on_stop(self):
        pass

    def open_settings(self, *args):
        return False
コード例 #18
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")
コード例 #19
0
class Operations():

    #This function opens the popup window for editing a stickynotes details
    def open_edit_mode(self, instance, *args):
        self.current_open = instance
        self.popup_card = MDCard(
            size=(200, 200),
            size_hint=(None, None),
            md_bg_color=(0.1, 0.1, 0.1, 1),
            radius=(20, 20, 20, 20),
        )

        self.layout = ModalView(
            size=(500, 500),
            size_hint=(None, None),
            background_color=(0, 0, 0, .9),
            background='atlas://data/images/defaulttheme/action_item')
        self.layout.add_widget(self.popup_card)
        #Get the full info of a sticky note from database using id
        mycursor.execute("SELECT * FROM " + current_user + ' WHERE id=' +
                         instance.name)
        note_content = mycursor.fetchone()

        #create an object self.details that holds the ui of the popup window
        self.details = Details()
        #Set the content of the sticky note
        self.details.ids.content.text = note_content[1]
        #set the color of the sticky note in the drop down menu based on value
        if note_content[3] == 1:
            self.details.ids.color.text = 'Dark Red'
        elif note_content[3] == 2:
            self.details.ids.color.text = 'Orange'
        elif note_content[3] == 3:
            self.details.ids.color.text = 'Yellow'
        elif note_content[3] == 4:
            self.details.ids.color.text = 'Green'
        elif note_content[3] == 5:
            self.details.ids.color.text = 'Peach'
        elif note_content[3] == 6:
            self.details.ids.color.text = 'Blue-Green'
        elif note_content[3] == 7:
            self.details.ids.color.text = 'Purple'
        elif note_content[3] == 8:
            self.details.ids.color.text = 'Light-Purple'
        elif note_content[3] == 9:
            self.details.ids.color.text = 'Pink'
        #bind save and delete functions to their respective buttons
        self.details.ids.save.bind(
            on_press=partial(Operations.save_changes, self, 1))
        self.details.ids.delete.bind(
            on_press=partial(Operations.deletion, self))
        #define the elements for the menu of colors
        items = [{
            'text': 'Dark Red'
        }, {
            'text': 'Orange'
        }, {
            'text': 'Yellow'
        }, {
            'text': 'Green'
        }, {
            'text': 'peach'
        }, {
            'text': 'Blue-Green'
        }, {
            'text': 'Purple'
        }, {
            'text': 'Light-Purple'
        }, {
            'text': 'Pink'
        }]
        #define the menue
        self.details.menu = MDDropdownMenu(caller=self.details.ids.color,
                                           position="auto",
                                           width_mult=4,
                                           items=items)
        self.details.menu.bind(on_release=partial(Operations.set_color, self))
        #Add the ui to the popup card
        self.popup_card.add_widget(self.details)
        #open the popup card
        self.layout.open()
        #some animation for the opening of the popup card
        anim1 = Animation(
            opacity=1,
            duration=.2,
        )
        anim2 = Animation(size=(500, 500), duration=.2)
        anim1.start(self.popup_card)
        anim2.start(self.popup_card)

    #This function is called when a new sticky note is to be created,uses same
    #structure for ui for the edit view popup card
    def open_create_mode(self, instance):
        self.popup_card = MDCard(
            size=(200, 200),
            size_hint=(None, None),
            md_bg_color=(0.1, 0.1, 0.1, 1),
            radius=(20, 20, 20, 20),
        )

        self.layout = ModalView(
            size=(500, 500),
            size_hint=(None, None),
            background_color=(0, 0, 0, .9),
            background='atlas://data/images/defaulttheme/action_item')
        self.layout.add_widget(self.popup_card)
        self.details = Details()
        self.details.remove_widget(self.details.ids.delete)
        items = [{
            'text': 'Dark Red'
        }, {
            'text': 'Orange'
        }, {
            'text': 'Yellow'
        }, {
            'text': 'Green'
        }, {
            'text': 'peach'
        }, {
            'text': 'Blue-Green'
        }, {
            'text': 'Purple'
        }, {
            'text': 'Light-Purple'
        }, {
            'text': 'Pink'
        }]
        self.details.menu = MDDropdownMenu(caller=self.details.ids.color,
                                           position="auto",
                                           width_mult=4,
                                           items=items)
        #bind a function that changes the text of the texfield when the user selects a color
        self.details.menu.bind(on_release=partial(Operations.set_color, self))
        self.popup_card.add_widget(self.details)
        self.layout.open()
        anim1 = Animation(
            opacity=1,
            duration=.2,
        )
        anim2 = Animation(size=(500, 500), duration=.2)
        anim1.start(self.popup_card)
        anim2.start(self.popup_card)
        #Bind the save sticky note function to the save button of the ui
        self.details.ids.save.bind(
            on_press=partial(Operations.save_changes, self, 2))

    #function that sets the text of the textfield after user selects color
    def set_color(self, menu, menu_item):
        self.details.ids.color.text = menu_item.text
        menu.dismiss()

    def save_changes(self, id, caller):
        #if we are just upadting info then delete original entry in db and insert new data
        if id == 1:
            name = self.current_open.name
            mycursor.execute("DELETE FROM " + current_user + ' WHERE id=' +
                             name)
            mydb.commit()
        #inserting new data as new row in db using a random id
        new_id = random.random()
        new_content = self.details.ids.content.text
        new_date = date.today().strftime('%Y-%m-%d')
        if self.details.ids.color.text == 'Dark Red':
            new_color = 1
        elif self.details.ids.color.text == 'Orange':
            new_color = 2
        elif self.details.ids.color.text == 'Yellow':
            new_color = 3
        elif self.details.ids.color.text == 'Green':
            new_color = 4
        elif self.details.ids.color.text == 'peach':
            new_color = 5
        elif self.details.ids.color.text == 'Blue-Green':
            new_color = 6
        elif self.details.ids.color.text == 'Purple':
            new_color = 7
        elif self.details.ids.color.text == 'Light-Purple':
            new_color = 8
        elif self.details.ids.color.text == 'Pink':
            new_color = 9

        #inserting data into table of db
        new_data = (new_id, new_content, new_date, new_color)
        mycursor.execute(
            'INSERT INTO ' + current_user + ' VALUES(%s,%s,%s,%s)', new_data)
        mydb.commit()
        #close popup window
        self.layout.dismiss()
        Mainscreenvar = sm.get_screen("MainScreen")
        #clear mainview to rflect new changes to any stickynote
        Mainscreenvar.ids.container.clear_widgets()
        NotesLoader.notes_loader(self)

    #Function called when a sticky note needs to be deleted
    def deletion(self, caller):
        name = self.current_open.name
        mycursor.execute("DELETE FROM " + current_user + " WHERE id= " + name)
        mydb.commit()
        Mainscreenvar = sm.get_screen("MainScreen")
        Mainscreenvar.ids.container.clear_widgets()
        self.layout.dismiss()
        NotesLoader.notes_loader(self)
コード例 #20
0
class RecycleCarousel(FloatLayout):
    """
    Wrapper class for a :class:`~kivy.uix.carousel.Carousel` that uses only 3 slides to update content dynamically.

    The :attr:`index` is updated according to the change of the carousel index and each time one of the slides is
    updated with data from :attr:`data`. The content of the slides is constructed as instances of :attr:`viewclass`.
    """

    carousel = ObjectProperty()
    """:class:`kivy.properties.ObjectProperty` defaults to ``None``."""
    viewclass = StringProperty("TransCard")
    """:class:`kivy.properties.StringProperty` defaults to ``"TransCard"``. Class name of the widgets that are added
    to the carousel."""
    data = ListProperty()
    """:class:`kivy.properties.ListProperty` defaults to ``None``. List of dictionaries from which the content is
    generated."""
    slide_width = NumericProperty()
    """:class:`kivy.properties.NumericProperty` defaults to ``None``. Width that the content of the slides should
    have."""
    dynamic_height = BooleanProperty(False)
    """:class:`kivy.properties.BooleanProperty` defaults to ``False``. If ``True`` updates the height of the root
    widget to the height of the object on the current slide + 24. Only possible if size_hint_y of the widget on the
    slide is not set."""
    index = NumericProperty(0)
    """:class:`kivy.properties.NumericProperty` defaults to ``0``. Current (virtual) index."""
    last_carousel_index = NumericProperty(0)
    """:class:`kivy.properties.NumericProperty` defaults to ``0``. Last index that the :attr:`carousel` had. Used to
    determine whether the user did slide right or left."""
    current_slide = ObjectProperty()
    """:class:`kivy.properties.ObjectProperty`. Reference to :attr:`carousel`.current_slide."""

    modal_layout_name = StringProperty()
    """:class:`kivy.properties.StringProperty` defaults to ``None``. Class name for root widget of :attr:`modal`."""
    modal_data_cls_name = StringProperty()
    """:class:`kivy.properties.StringProperty` defaults to ``None``. Class name for children of :attr:`modal`."""
    modal = ObjectProperty(ModalView())
    """:class:`kivy.properties.ObjectProperty` defaults to ``ModalView()``."""
    default_modal_size_hint = ListProperty([1, None])

    def update_height(self, *_):
        """Update height via animation, so that Widget has height of currently displayed card."""
        if self.dynamic_height:
            new_height = self.carousel.current_slide.height + 24
            if self.height != new_height:
                anim = Animation(height=new_height, duration=0.3)
                anim.start(self)

    def setup_modal(self):
        """Return root widget to display on the modal."""
        self.modal = ModalView()
        modal_root_cls = Factory.get(self.modal_layout_name)
        modal_root = modal_root_cls()
        self.modal.add_widget(modal_root)

    def _modal_child_callback(self, i, *_):
        self.set_index(i)
        self.modal.dismiss()

    def update_modal_content(self):
        """Update content of modal."""
        data_dicts = [{
            **dict,
            "size_hint": self.default_modal_size_hint,
            "on_press": partial(self._modal_child_callback, i),
        } for i, dict in enumerate(self.data)]
        self.modal.children[0].child_class_name = self.modal_data_cls_name
        self.modal.children[0].data = data_dicts

    def get_checked(self, attribute_name=None):
        """If ``attribute_name`` is ``None``, return currently selected widget, else return a property thereof."""
        checked_elements = [self.carousel.current_slide]
        if attribute_name is None:
            return checked_elements
        return [
            getattr(element, attribute_name) for element in checked_elements
            if element
        ]

    def open_menu(self, *_):
        """Open :class:`kivy.uix.modalview.ModalView` with content given by :meth:`setup_modal`."""
        if not self.modal.children:
            self.setup_modal()
        self.update_modal_content()
        self.modal.open()

    def on_data(self, *_):
        """Set up :attr:`carousel` by initializing 3 widgets, adding them and binding some Properties."""
        self.carousel.clear_widgets()
        if len(self.data) >= 3:
            for i in [0, 1, -1]:
                widget = Factory.get(self.viewclass)(**self.data[i])
                self.carousel.add_widget(widget)
                self.bind(slide_width=widget.setter("width"))
                widget.bind(on_press=self.open_menu)
                widget.width = self.slide_width
            self.carousel.register_event_type("on_index")
            self.carousel.bind(index=self.update_index)
            self.carousel.bind(current_slide=self.update_height)
            self.carousel.current_slide.bind(height=self.update_height)
        print(
            "RecylceCarousel needs at least 3 elements to be displayed correctly."
        )

    def update_index(self, _, carousel_index):
        """Change :attr:`index` according to change in ``carousel_index`` and update one of the three slides."""
        diff = carousel_index - self.last_carousel_index
        diff = -1 if diff == 2 else 1 if diff == -2 else diff
        self.last_carousel_index = carousel_index
        self.index = (self.index + diff) % len(self.data)
        self.update_slide(carousel_index + diff, self.index + diff)

    def update_slide(self, carousel_index, index):
        """
        Update slide with index ``carousel_index`` by content from :attr:`data` [index].

        Modulo function applied to indices guarantees values to be in the correct range.
        """
        carousel_index %= 3
        index %= len(self.data)
        for name, val in self.data[index].items():
            setattr(self.carousel.slides[carousel_index], name, val)

    def set_index(self, index):
        """Set :attr:`index` to ``index`` and updates carousel accordingly."""
        self.index = index
        self.update_height()
        for i in [0, 1, -1]:
            self.update_slide((self.last_carousel_index + i) % 3,
                              self.index + i)
コード例 #21
0
ファイル: main.py プロジェクト: Xayom/Battleship_Kivy
class BoardScreen2(Screen):
    status = ListProperty([0 for i in range(100)])
    coords = ListProperty([0, 0])
    popup1 = ModalView(size_hint=(0.3, 0.0), auto_dismiss=False)
    popup1.pos_hint = {'x': 0.35, 'y': 0.9}
    popup1.add_widget(Label(text='Computers Turn, Please wait...', font_size=26))
    current = 0
    sound = ''

    def on_enter(self):
        global ENTRY_COMP

        if ENTRY_COMP == 0:
            ENTRY_COMP = 1
            self.ids.grid.top = 760
            self.ids.grid.right = 1350

            for i in range(NUMBER_OF_BUTTONS):
                for j in range(NUMBER_OF_BUTTONS):
                    button = Button(text="")
                    button.coords = (i, j)
                    button.bind(on_press=self.button_pressed)
                    self.ids.grid.add_widget(button)

    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()

    # def somefunc(self, *args):
    #     self.manager.current = 'main'
    #
    def button_pressed(self, button):
        if button.text == 'YES':
            self.manager.current = 'main'
            self.popup.dismiss()
        else:
            global CURRENT_PLAYER, AMOUNT, CURRENT1, SOME_LIST1, finish
            row, column = button.coords
            status_index = row * 10 + column
            already_played = self.status[status_index]
            if not already_played and CURRENT_PLAYER == 1:
                self.status[status_index] = CURRENT_PLAYER

                for ship in SHIPS_OF_COMP:
                    if ship[0] == (row, column):
                        CURRENT1 += 1
                        SOME_LIST1.append((row, column))
                        button.background_color = ship[1]
                        # button.text = str(ship[2])
                        if CURRENT1 == ship[2]:
                            if self.sound != '':
                                self.sound.stop()
                            self.sound = SoundLoader.load('files/boom.mp3')
                            self.sound.play()

                            for ship in SOME_LIST1:
                                x, y = ship
                                s = [1, 0, -1]
                                t = [1, 0, -1]
                                for xx in s:
                                    for yy in t:
                                        for child in self.ids.grid.children:
                                            if child.coords == (x + xx, y + yy) and (x + xx, y + yy) not in SOME_LIST1:
                                                child.text = 'X'
                                                child.background_color = [1, 0, 0, 1]
                            SOME_LIST1 = []
                            CURRENT1 = 0
                        else:
                            if self.sound != '':
                                self.sound.stop()
                            self.sound = SoundLoader.load('files/bomb2.wav')
                            self.sound.play()

                        AMOUNT += 1
                        AMOUNT = 4 + 3 * 2 + 2 * 3 + 4
                        if AMOUNT == 4 + 3 * 2 + 2 * 3 + 4:
                            finish = SoundLoader.load('files/winner.mp3')
                            finish.play()
                            winner = ModalView(size_hint=(0.75, 0.5))
                            winner.background = 'files/youWin.png'
                            # victory_label = Label(text='You WIN!!!!!', font_size=50)
                            # winner.add_widget(victory_label)
                            winner.bind(on_dismiss=self.somefunc)
                            winner.open()
                        break

                if button.background_color == [1, 1, 1, 1]:
                    button.text = 'X'
                    if self.sound != '':
                        self.sound.stop()
                    self.sound = SoundLoader.load('files/Not_ship.wav')
                    self.sound.play()

                    button.background_color = [1, 0, 0, 1]
                    Clock.schedule_once(self.callback, 1)
                    CURRENT_PLAYER *= -1

    def callback(self, dt):
        self.manager.current = 'board1'
        self.popup1.open()
        self.current = 0
        Clock.schedule_interval(self.my_callback, 1.0)

    def callback1(self, dt):
        if dt >= 0.9:
            self.manager.get_screen('board1').popup.dismiss()
            self.manager.current = 'board2'
        else:
            self.manager.get_screen('board1').popup.open()
            Clock.schedule_once(self.callback1, 1)

    def somefunc(self, *args):
        finish.stop()
        self.manager.current = 'main'

    def my_callback(self, dt):
        self.current += dt
        if self.current > 2:
            global CURRENT_PLAYER, LIST_OF_TARGETS1, LIST_OF_TARGETS, CURRENT, SOME_LIST, AMOUNT1, finish
            grid = self.manager.get_screen('board1').ids.grid
            rand = random.randint(0, len(LIST_OF_TARGETS) - 1)
            TARGETS = LIST_OF_TARGETS
            if len(LIST_OF_TARGETS1):
                rand = random.randint(0, len(LIST_OF_TARGETS1) - 1)
                TARGETS = LIST_OF_TARGETS1

            for child in grid.children:
                if child.coords == TARGETS[rand]:
                    if child.background_color == [1, 1, 1, 1]:
                        child.text = 'X'
                        child.background_color = [1, 0, 0, 1]
                        self.popup1.dismiss()
                        Clock.unschedule(self.my_callback)
                        CURRENT_PLAYER *= -1
                        self.sound.stop()
                        self.sound = SoundLoader.load('files/Not_ship.wav')
                        self.sound.play()
                        Clock.schedule_once(self.callback1, 0.7)
                        TARGETS.remove(child.coords)
                    else:
                        x, y = child.coords
                        CURRENT += 1
                        AMOUNT1 += 1
                        SOME_LIST.append((x, y))

                        if (x + 1, y + 1) in TARGETS:
                            TARGETS.remove((x + 1, y + 1))
                        if (x - 1, y - 1) in TARGETS:
                            TARGETS.remove((x - 1, y - 1))
                        if (x + 1, y - 1) in TARGETS:
                            TARGETS.remove((x + 1, y - 1))
                        if (x - 1, y + 1) in TARGETS:
                            TARGETS.remove((x - 1, y + 1))

                        if (x + 1, y + 1) in LIST_OF_TARGETS:
                            LIST_OF_TARGETS.remove((x + 1, y + 1))
                        if (x - 1, y - 1) in LIST_OF_TARGETS:
                            LIST_OF_TARGETS.remove((x - 1, y - 1))
                        if (x + 1, y - 1) in LIST_OF_TARGETS:
                            LIST_OF_TARGETS.remove((x + 1, y - 1))
                        if (x - 1, y + 1) in LIST_OF_TARGETS:
                            LIST_OF_TARGETS.remove((x - 1, y + 1))

                        if (x + 1, y) not in LIST_OF_TARGETS1 and (x + 1, y) in LIST_OF_TARGETS:
                            LIST_OF_TARGETS1.append((x + 1, y))
                            LIST_OF_TARGETS.remove((x + 1, y))
                        if (x - 1, y) not in LIST_OF_TARGETS1 and (x - 1, y) in LIST_OF_TARGETS:
                            LIST_OF_TARGETS1.append((x - 1, y))
                            LIST_OF_TARGETS.remove((x - 1, y))
                        if (x, y - 1) not in LIST_OF_TARGETS1 and (x, y - 1) in LIST_OF_TARGETS:
                            LIST_OF_TARGETS1.append((x, y - 1))
                            LIST_OF_TARGETS.remove((x, y - 1))
                        if (x, y + 1) not in LIST_OF_TARGETS1 and (x, y + 1) in LIST_OF_TARGETS:
                            LIST_OF_TARGETS1.append((x, y + 1))
                            LIST_OF_TARGETS.remove((x, y + 1))

                        child.background_color = [0, 1, 0, 1]
                        AMOUNT1 = 4 + 3 * 2 + 2 * 3 + 4
                        if AMOUNT1 == 4 + 3 * 2 + 2 * 3 + 4:
                            self.popup1.dismiss()
                            Clock.unschedule(self.my_callback)
                            finish = SoundLoader.load('files/proval.mp3')
                            finish.play()
                            winner = ModalView(size_hint=(0.75, 0.5))
                            winner.background = 'files/You_Lost.png'
                            # victory_label = Label(text='You Lost!!!!!', font_size=50)
                            # winner.add_widget(victory_label)
                            winner.bind(on_dismiss=self.somefunc)
                            winner.open()
                            return

                        TARGETS.remove((x, y))
                        if CURRENT == int(child.name):
                            LIST_OF_TARGETS1[:] = []
                            if self.sound != '':
                                self.sound.stop()
                            self.sound = SoundLoader.load('files/boom.mp3')
                            self.sound.play()

                            for ship in SOME_LIST:
                                x, y = ship
                                s = [1, 0, -1]
                                t = [1, 0, -1]
                                for xx in s:
                                    for yy in t:
                                        for child in grid.children:
                                            if child.coords == (x + xx, y + yy) and (x + xx, y + yy) not in SOME_LIST:
                                                child.text = 'X'
                                                child.background_color = [1, 0, 0, 1]
                            SOME_LIST = []
                            CURRENT = 0
                        else:
                            if self.sound != '':
                                self.sound.stop()
                            self.sound = SoundLoader.load('files/bomb2.wav')
                            self.sound.play()
                        self.current = 0
                    return

        child = self.popup1.children[0]
        if child.text[-1:-4:-1] == '...':
            child.text = child.text[:-3]
        else:
            child.text += '.'

    def on_status(self, instance, new_value):
        status = new_value
コード例 #22
0
ファイル: main.py プロジェクト: rusticmystic/KivyMD
class KitchenSink(App, Screens):
    theme_cls = ThemeManager()
    theme_cls.primary_palette = 'BlueGray'
    theme_cls.accent_palette = 'Gray'
    previous_date = ObjectProperty()
    title = "Kitchen Sink"
    theme_cls.theme_style = 'Dark'

    def __init__(self, **kwargs):
        super().__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_app_bar = None
        self.instance_menu_demo_apps = 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.my_snackbar = None
        self._interval = 0
        self.tick = 0
        self.x = 0
        self.y = 25
        self.create_stack_floating_buttons = False
        self.hex_primary_color = get_hex_from_color(
            self.theme_cls.primary_color)
        self.previous_text = \
            f"Welcome to the application [b][color={self.hex_primary_color}]" \
            f"Kitchen Sink[/color][/b].\nTo see [b]" \
            f"[color={self.hex_primary_color}]KivyMD[/color][/b] " \
            f"examples, open the menu and select from the list the desired " \
            f"example or"
        self.previous_text_end = \
            f"for show example apps\n\n" \
            f"Author - [b][color={self.hex_primary_color}]" \
            f"Andrés Rodríguez[/color][/b]\n" \
            f"[u][b][color={self.hex_primary_color}]" \
            f"[email protected][/color][/b][/u]\n\n" \
            f"Author this Fork - [b][color={self.hex_primary_color}]" \
            f"Ivanov Yuri[/color][/b]\n" \
            f"[u][b][color={self.hex_primary_color}]" \
            f"[email protected][/color][/b][u]"
        self.names_contacts = ('Alexandr Taylor', 'Yuri Ivanov',
                               'Robert Patric', 'Bob Marley', 'Magnus Carlsen',
                               'Jon Romero', 'Anna Bell', 'Maxim Kramerer',
                               'Sasha Gray', 'Vladimir Ivanenko')
        self.demo_apps_list = [
            'Shop Window', 'Coffee Menu', 'Fitness Club', 'Registration',
            'Account Page'
        ]
        self.menu_for_demo_apps = []
        self.list_name_icons = list(md_icons.keys())[0:15]
        Window.bind(on_keyboard=self.events)
        crop_image((Window.width, int(dp(Window.height * 35 // 100))),
                   f'{self.directory}/assets/guitar-1139397_1280.png',
                   f'{self.directory}/assets/guitar-1139397_1280_crop.png')

    def set_list_for_refresh_layout(self):
        async def set_list_for_refresh_layout():
            names_icons_list = list(md_icons.keys())[self.x:self.y]
            for name_icon in names_icons_list:
                await asynckivy.sleep(0)
                self.data['Refresh Layout']['object'].\
                    ids.box.add_widget(ItemForListRefreshLayout(
                        icon=name_icon, text=name_icon))
            self.data['Refresh Layout'][
                'object'].ids.refresh_layout.refresh_done()

        asynckivy.start(set_list_for_refresh_layout())

    def refresh_callback(self, *args):
        """A method that updates the state of your application
        while the spinner remains on the screen."""
        def refresh_callback(interval):
            self.data['Refresh Layout']['object'].\
                ids.box.clear_widgets()
            if self.x == 0:
                self.x, self.y = 25, 50
            else:
                self.x, self.y = 0, 25
            self.set_list_for_refresh_layout()
            self.tick = 0

        Clock.schedule_once(refresh_callback, 1)

    def build_tabs(self):
        for name_tab in self.list_name_icons:
            tab = Factory.MyTab(text=name_tab)
            self.data['Tabs']['object'].ids.android_tabs.add_widget(tab)

    def switch_tabs_to_icon(self, istance_android_tabs):
        for i, instance_tab in enumerate(
                istance_android_tabs.ids.scrollview.children[0].children):
            istance_android_tabs.ids.scrollview.children[0].remove_widget(
                instance_tab)
            istance_android_tabs.add_widget(
                Factory.MyTab(text=self.list_name_icons[i]))

    def switch_tabs_to_text(self, istance_android_tabs):
        for instance_tab in istance_android_tabs.ids.scrollview.children[
                0].children:
            for k, v in md_icons.items():
                if v == instance_tab.text:
                    istance_android_tabs.ids.scrollview.children[
                        0].remove_widget(instance_tab)
                    istance_android_tabs.add_widget(
                        Factory.MyTab(
                            text=' '.join(k.split('-')).capitalize()))
                    break

    def crop_image_for_tile(self, instance, size, path_to_crop_image):
        """Crop images for Grid screen."""

        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.pickers 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(f'{text} to {content.name_item}')

        content = ContentForAnimCard(callback=callback)

        for name_contact in self.names_contacts:
            self.data['Accordion List']['object'].ids.anim_list.add_widget(
                MDAccordionListItem(content=content,
                                    icon='assets/kivy-logo-white-512.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.data['Download File']['object'].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):
        """Adds MDCardPost objects to the screen Cards
        when the screen is open."""

        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="H5",
                    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):
        """Set new label on the screen UpdateSpinner."""
        def update_screen(interval):
            self.tick += 1
            if self.tick > 2:
                instance.update = True
                self.tick = 0
                self.data['Update Screen Widget']['object'].\
                    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)
        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.data['Popup Screen']['object'].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 show_user_example_animation_card(self):
        """Create and open instance MDUserAnimationCard
        for the screen UserCard."""

        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):
        """Create and show instance Snackbar for the screen MySnackBar."""
        def callback(instance):
            toast(instance.text)

        def wait_interval(interval):
            self._interval += interval
            if self._interval > self.my_snackbar.duration:
                anim = Animation(y=dp(10), d=.2)
                anim.start(self.data['Snackbars']['object'].ids.button)
                Clock.unschedule(wait_interval)
                self._interval = 0
                self.my_snackbar = None

        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=callback).show()
        elif snack_type == 'verylong':
            Snackbar(text="This is a very very very very very very very "
                     "long snackbar!").show()
        elif snack_type == 'float':
            if not self.my_snackbar:
                self.my_snackbar = Snackbar(text="This is a snackbar!",
                                            button_text='Button',
                                            duration=3,
                                            button_callback=callback)
                self.my_snackbar.show()
                anim = Animation(y=dp(72), d=.2)
                anim.bind(on_complete=lambda *args: Clock.schedule_interval(
                    wait_interval, 0))
                anim.start(self.data['Snackbars']['object'].ids.button)

    def show_example_input_dialog(self):
        """Creates an instance of the dialog box and displays it
        on the screen for the screen Dialogs."""
        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_date(self, instance, time):
        """Get date for MDTimePicker from the screen Pickers."""

        self.data['Pickers']['object'].ids.time_picker_label.text = str(time)
        self.previous_time = time

    def show_example_time_picker(self):
        """Show MDTimePicker from the screen Pickers."""

        from kivymd.pickers import MDTimePicker

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

        if self.data['Pickers']['object'].\
                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):
        """Set previous date for MDDatePicker from the screen Pickers."""

        self.previous_date = date_obj
        self.data['Pickers']['object'].\
            ids.date_picker_label.text = str(date_obj)

    def show_example_date_picker(self):
        """Show MDDatePicker from the screen Pickers."""

        from kivymd.pickers import MDDatePicker

        if self.data['Pickers']['object'].\
                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):
        """Show menu from the screen BottomSheet."""

        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):
        """Show menu from the screen BottomSheet."""

        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_title_toolbar(self, title):
        """Set string title in MDToolbar for the whole application."""

        self.main_widget.ids.toolbar.title = title

    def set_appbar(self):
        """Create MDBottomAppBar for the screen BottomAppBar."""

        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):
        """Sets icons in MDBottomAppBar for the screen BottomAppBar."""

        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 show_password(self, field, button):
        """
        Called when you press the right button in the password field
        for the screen TextFields.

        instance_field: kivy.uix.textinput.TextInput;
        instance_button: kivymd.button.MDIconButton;

        """

        # Show or hide text of password, set focus field
        # and set icon of right button.
        field.password = not field.password
        field.focus = True
        button.icon = 'eye' if button.icon == 'eye-off' else 'eye-off'

    def set_error_message(self, *args):
        """Checks text of TextField with type "on_error"
        for the screen TextFields."""

        text_field_error = args[0]
        if len(text_field_error.text) == 2:
            text_field_error.error = True
        else:
            text_field_error.error = False

    def set_list_md_icons(self, text='', search=False):
        """Builds a list of icons for the screen MDIcons."""
        def add_icon_item(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
                })

        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:
                    add_icon_item(name_icon)
            else:
                add_icon_item(name_icon)

    def set_menu_for_demo_apps(self):
        if not len(self.menu_for_demo_apps):
            for name_item in self.demo_apps_list:
                self.menu_for_demo_apps.append({
                    'viewclass':
                    'OneLineListItem',
                    'text':
                    name_item,
                    'on_release':
                    lambda x=name_item: self.show_demo_apps(x)
                })

    def show_demo_apps(self, name_item):
        self.show_screens_demo(name_item)
        self.main_widget.ids.scr_mngr.current = name_item.lower()
        self.instance_menu_demo_apps.dismiss()

    def on_pause(self):
        return True

    def on_stop(self):
        pass

    def open_settings(self, *args):
        return False
コード例 #23
0
ファイル: material_gui.py プロジェクト: LoreBerli/exif_viewer
class Exif_view(App):
    theme_cls = ThemeManager()
    previous_date = ObjectProperty()
    title = "Exif_Viewer"

    menu_items = [
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
        {
            'viewclass': 'MDMenuItem',
            'text': 'Example item'
        },
    ]

    def build(self):
        main_widget = Builder.load_string(main_widget_kv)
        self.theme_cls.accent_palette = 'Indigo'
        self.manager = None
        self.state = State.State()
        self.im = self.state.current_img
        keyboard = Window.request_keyboard(self._keyboard_released, self.root)
        keyboard.bind(on_key_down=self._keyboard_on_key_down,
                      on_key_up=self._keyboard_released)

        self.bottom_navigation_remove_mobile(main_widget)
        toast("Click on the + botton to open a image")
        return main_widget

    def _keyboard_released(self, window, keycode):
        pass

    def _keyboard_on_key_down(self, window, keycode, text, super):
        if keycode[1] == 'r':
            self.root.ids['imagde'].rota()
        if keycode[1] == 'left':
            self.state.roll(1)
            self.change_image(self.state.current_img.path)
        if keycode[1] == 'right':
            self.state.roll(-1)
            self.change_image(self.state.current_img.path)

    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 change_image(self, path):
        self.state.change_current(path)
        self.root.ids['image'].source = self.state.current_img.path
        self.root.ids['imagde'].source = self.state.current_img.path
        self.state.must_update = True
        self.fill_exif()
        toast(path)

    def file_manager_open(self):
        import os
        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,
                                              ext=['.jpg', '.jpeg'])
            self.manager.add_widget(self.file_manager)
            self.file_manager.show(os.getcwd())  # output manager to the screen
        self.state.cwd = self.file_manager.current_path + "/"
        self.manager_open = True
        self.manager.open()

    def select_path(self, path):
        self.change_image(path)
        self.exit_manager()
        self.root.ids.scr_mngr.current = 'data'

    def fill_exif(self):
        img = self.state.current_img
        dt = img.exif
        self.root.ids['ml'].clear_widgets()
        for v in dt:
            self.root.ids['ml'].add_widget(
                kivymd.list.ThreeLineRightIconListItem(text=v,
                                                       secondary_text=str(
                                                           dt[v])))

    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

    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 on_pause(self):
        return True

    def on_stop(self):
        pass
コード例 #24
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
            ])
コード例 #25
0
class NewPublicationScreen(Screen):
    def __init__(self, **kwargs):
        super(NewPublicationScreen, self).__init__(**kwargs)
        # File manager
        self.fmanager = None
        self.fmanager_open = False

        self.date_of_publication = self.ids["date_of_publication"]
        self.main_button_publication = self.ids["main_button_publication"]
        self.custom_city = self.ids["custom_city"]
        self.custom_publisher = self.ids["custom_publisher"]
        self.custom_upload = self.ids["custom_upload"]
        self.custom_authors = self.ids["custom_authors"]
        # City
        self.menu_for_city = []
        self.instance_menu_city = None
        self.menu_for_ct = []
        # Publisher
        self.menu_for_publisher = []
        self.instance_menu_publisher = None
        self.menu_for_pb = []

        # Publication type
        self.menu_for_publication_type = [
            "Book", "Conference proceedings", "Journal"
        ]
        self.instance_menu_publication_type = None
        self.menu_for_pt = []

        # Authors
        self.menu_for_authors = []
        self.instance_menu_authors = None
        self.menu_for_au = []
        self.main_button_author = self.ids["main_button_author"]

        # Entries
        self.book_title = self.ids["book_title"]
        self.edition = self.ids["edition"]
        self.journal_title = self.ids["journal_title"]
        self.volume = self.ids["volume"]
        self.conf_title = self.ids["conf_title"]

        # dicts
        self.author_dictionary = {}
        self.city_dictionary = {}
        self.publisher_dictionary = {}

    def on_enter(self, *args):
        self.setup_authors()
        self.setup_city()
        self.setup_publisher()

    def setup_authors(self):
        self.author_dictionary = database_interface.get_authors()
        if len(self.author_dictionary) > 0:
            for k, v in self.author_dictionary.items():
                self.menu_for_authors.append(k)

    def setup_city(self):
        self.city_dictionary = database_interface.get_cities()
        if len(self.city_dictionary) > 0:
            for k, v in self.city_dictionary.items():
                self.menu_for_city.append(k)

    def setup_publisher(self):
        self.publisher_dictionary = database_interface.get_publishers()
        if len(self.publisher_dictionary) > 0:
            for k, v in self.publisher_dictionary.items():
                self.menu_for_publisher.append(k)

    def set_menu_for_city(self):
        # reset menu_for_author_titles and get from db
        if len(self.menu_for_city) < 1:
            return
        self.menu_for_ct = []
        for name_item in self.menu_for_city:
            self.menu_for_ct.append({
                "viewclass":
                "OneLineListItem",
                "text":
                name_item,
                "on_release":
                lambda x=name_item: self.chosen_city(x),
            })

    def chosen_city(self, x):
        self.custom_city.text = x
        self.instance_menu_city.dismiss()

    def set_menu_for_publisher(self):
        # reset menu_for_author_titles and get from db
        if len(self.menu_for_publisher) < 1:
            return
        self.menu_for_pb = []
        for name_item in self.menu_for_publisher:
            self.menu_for_pb.append({
                "viewclass":
                "OneLineListItem",
                "text":
                name_item,
                "on_release":
                lambda x=name_item: self.chosen_publisher(x),
            })

    def chosen_publisher(self, x):
        self.instance_menu_publisher.dismiss()
        self.custom_publisher.text = x

    def set_menu_for_publication(self):
        # reset menu_for_author_titles and get from db
        if len(self.menu_for_publication_type) < 1:
            return
        self.menu_for_pt = []
        for name_item in self.menu_for_publication_type:
            self.menu_for_pt.append({
                "viewclass":
                "OneLineListItem",
                "text":
                name_item,
                "on_release":
                lambda x=name_item: self.chosen_publication_type(x),
            })

    def chosen_publication_type(self, x):
        self.main_button_publication.text = x
        if x.lower() == "journal":
            self.journal_title.disabled = False
            self.volume.disabled = False
            self.edition.disabled = True
            self.book_title.disabled = True
            self.conf_title.disabled = True

        elif x.lower() == "book":
            self.edition.disabled = False
            self.book_title.disabled = False
            self.volume.disabled = True
            self.journal_title.disabled = True
            self.conf_title.disabled = True

        elif x.lower() == "conference proceedings":
            self.conf_title.disabled = False
            self.volume.disabled = True
            self.journal_title.disabled = True
            self.edition.disabled = True
            self.book_title.disabled = True

        self.instance_menu_publication_type.dismiss()

    def set_menu_for_authors(self):
        if len(self.menu_for_authors) < 1:
            return
        self.menu_for_au = []
        for name_item in self.menu_for_authors:
            self.menu_for_au.append({
                "viewclass":
                "OneLineListItem",
                "text":
                name_item,
                "on_release":
                lambda x=name_item: self.chosen_author(x),
            })

    def get_author_id_from_dict(self, name):
        try:
            return self.author_dictionary[name]
        except:
            return -1

    def get_publisher_id_from_dict(self, name):
        try:
            return self.publisher_dictionary[name]
        except:
            return -1

    def get_city_id_from_dict(self, name):
        try:
            return self.city_dictionary[name]
        except:
            return -1

    def chosen_author(self, x):
        # self.main_button_author.text = x
        if self.custom_authors.text == "":
            toAdd = x
            # self.custom_authors.text = x
        else:
            toAdd = x + "," + self.custom_authors.text
            # self.custom_authors.text = x + "," + self.custom_authors.text

        if toAdd.count(x) > 1:
            # re-entering, don't accept
            return
        self.custom_authors.text = toAdd

        self.instance_menu_authors.dismiss()

    def submit(self, pub_type, authors, publisher, book_title, edition,
               journal_title, volume, conf_title, city, dop, file_path,
               abstract):
        count = 0
        authors_split = authors.split(",")
        bk_id = None
        journal_id = None
        conf_id = None
        can_proceed = [False, "cannot continue adding"]
        publication_id = "unknown error"
        for author_name in authors_split:
            if count > 0 and isinstance(publication_id, int):
                output = database_interface.add_author_publication_junction(
                    self.get_author_id_from_dict(author_name), publication_id)
                print(output)
                continue

            if pub_type.lower() == "book":
                bk_id = database_interface.add_book(book_title, edition)
                if isinstance(bk_id, int):
                    can_proceed = [True, "book"]
                else:
                    toast(bk_id)
            elif pub_type.lower() == "conference proceedings":
                conf_id = database_interface.add_conf_proceeding(conf_title)
                if isinstance(conf_id, int):
                    can_proceed = [True, "conf"]
                else:
                    toast(conf_id)
            elif pub_type.lower() == "journal":
                journal_id = database_interface.add_journal(
                    journal_title, volume)
                if isinstance(journal_id, int):
                    can_proceed = [True, "journal"]
                else:
                    toast(journal_id)
            if can_proceed[0]:

                if can_proceed[1] == "book":
                    publication_id = database_interface.add_publication(
                        book_id=bk_id,
                        city_id=self.get_city_id_from_dict(city),
                        publisher_id=self.get_publisher_id_from_dict(
                            publisher),
                        date_of_pub=dop,
                        abstract=abstract,
                        file_path=file_path)
                elif can_proceed[1] == "conf":
                    publication_id = database_interface.add_publication(
                        conf_id=conf_id,
                        city_id=self.get_city_id_from_dict(city),
                        publisher_id=self.get_publisher_id_from_dict(
                            publisher),
                        date_of_pub=dop,
                        abstract=abstract,
                        file_path=file_path)
                elif can_proceed[1] == "journal":
                    publication_id = database_interface.add_publication(
                        journal_id=journal_id,
                        city_id=self.get_city_id_from_dict(city),
                        publisher_id=self.get_publisher_id_from_dict(
                            publisher),
                        date_of_pub=dop,
                        abstract=abstract,
                        file_path=file_path)

                if publication_id is not None:
                    count = count + 1
                    output = database_interface.add_author_publication_junction(
                        self.get_author_id_from_dict(author_name),
                        publication_id)
                    print(output)
                    toast(output)
                else:
                    print("publication id is none")
            else:
                print(can_proceed[1])

        # reset

    def set_date_of_publication(self, date_obj):
        self.date_of_publication.text = str(date_obj)

    def get_file_to_upload(self):
        if not self.fmanager:
            self.fmanager = ModalView(size_hint=(1, 1), auto_dismiss=False)
            self.file_manager = MDFileManager(exit_manager=self.exit_manager,
                                              select_path=self.select_path)
            self.fmanager.add_widget(self.file_manager)
            self.file_manager.show('/')  # output manager to the screen
        self.fmanager_open = True
        self.fmanager.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()
        self.custom_upload.text = path
        toast(path)

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

        self.fmanager.dismiss()
        self.fmanager_open = False

    def on_back_pressed(self, *args):
        UserInterface().change_screen("home_screen")
        UserInterface().manage_screens("new_publication_screen", "remove")
コード例 #26
0
ファイル: main.py プロジェクト: snaiffer/TreeNote
class MainScreen(Screen):
  def __init__(self, **kwargs):
    super(MainScreen, self).__init__(**kwargs)

    mainLayout = GridLayout(cols=1)

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

    self.add_widget(mainLayout)
    self.showTree()

    self.win = Window

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

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

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

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

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

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

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

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

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

  def addLeaf(self, *args):
    if self.textField.text != '':
      tree.curItem().add(Leaf(name=self.textField.text))
      self.textField.text = ''
      self.contextMenu.dismiss()
      self.showTree()
コード例 #27
0
class PitstopTimerView(BoxLayout, SettingsListener):
    '''
    Provides a pit stop timer that automatically activates when certain speed
    thresholds are met. 
    '''
    _STOPWATCH_TICK = 0.1
    _FLASH_INTERVAL = 0.25
    _FLASH_COUNT = 10
    _EXIT_SPEED_CONTAINER_SIZE_HINT = 0.3
    _TIMER_WIDGET_SIZE_HINT = 0.4
    _SPEED_ALERT_THRESHOLD = 0.85
    _POPUP_SIZE_HINT = (0.75, 0.8)

    exit_speed_color = ListProperty(ColorScheme.get_dark_background_translucent())
    title = StringProperty('')
    current_time = StringProperty(STOPWATCH_NULL_TIME)
    exit_speed = StringProperty('')
    current_speed = NumericProperty(None)
    current_lap = NumericProperty(None)

    Builder.load_string(STOPWATCH_LAYOUT)

    def __init__(self, databus, title='Pit Stop', **kwargs):
        super(PitstopTimerView, self).__init__(**kwargs)
        self.title = title
        self.databus = databus
        self._popup = None
        self._flash_count = 0
        self._start_time = 0.0
        self._currently_racing = False
        self._pitstop_trigger_speed = 0
        self._pitstop_exit_speed = 0
        self._pitstop_alert_speed = 0
        databus.addChannelListener(STOPWATCH_SPEED_CHANNEL, self.set_speed)
        databus.addChannelListener(STOPWATCH_CURRENT_LAP, self.set_current_lap)

    def _set_exit_speed_frame_visible(self, visible):
        '''
        Shows or hides the frame containing the exit speed indicator
        :param visible true if exit speed frame should be visible
        :type visible
        '''
        container = self.ids.exit_speed_frame_container
        frame_visible = self.exit_speed_frame in container.children
        if visible:
            if not frame_visible:
                container.add_widget(self.exit_speed_frame)
        else:
            if frame_visible:
                container.remove_widget(self.exit_speed_frame)

    def _format_stopwatch_time(self):
        '''
        Format current laptime for display
        '''
        return format_laptime(self._current_time / 60.0)

    def _toggle_exit_speed_alert(self, alert_color):
        '''
        Toggles the background color for the exit speed frame
        '''
        if self.exit_speed_color == alert_color:
            self.exit_speed_color = ColorScheme.get_dark_background_translucent()
        else:
            self.exit_speed_color = alert_color

    def _update_speed_color(self):
        '''
        Selects the appropriate color for the exit speed indicator based on 
        configured speed threshold
        '''
        if self.current_speed > self._pitstop_alert_speed:
            self.ids.speed_rect.rect_color = ColorScheme.get_error()
            self._toggle_exit_speed_alert(ColorScheme.get_error())
        elif self.current_speed > self._pitstop_alert_speed * self._SPEED_ALERT_THRESHOLD:
            self.ids.speed_rect.rect_color = ColorScheme.get_alert()
            self.exit_speed_color = ColorScheme.get_dark_background_translucent()
        else:
            self.ids.speed_rect.rect_color = ColorScheme.get_happy()
            self.exit_speed_color = ColorScheme.get_dark_background_translucent()

    def _tick_stopwatch(self, *args):
        '''
        Increment the current stopwatch time
        '''
        self._current_time = time() - self._start_time
        self.current_time = self._format_stopwatch_time()
        self.exit_speed = '{}'.format(int(self.current_speed))
        if self.current_speed > self._pitstop_trigger_speed:
            self._set_exit_speed_frame_visible(True)
        self._update_speed_color()

    def _stop_stopwatch(self):
        '''
        Stops the stopwatch timer
        '''
        Clock.unschedule(self._tick_stopwatch)
        self.current_time = STOPWATCH_NULL_TIME

    def _in_race_mode(self):
        '''
        Return True if we think we're in 'racing mode'
        '''
        return self.current_speed > self._pitstop_exit_speed and\
            self.current_lap > 0

    def user_preferences_updated(self, user_preferences):
        '''
        Update runtime values from user preferences
        '''
        self._pitstop_timer_enabled = user_preferences.get_pref_bool('dashboard_preferences', 'pitstoptimer_enabled')
        self._pitstop_trigger_speed = user_preferences.get_pref_int('dashboard_preferences', 'pitstoptimer_trigger_speed')
        self._pitstop_exit_speed = user_preferences.get_pref_int('dashboard_preferences', 'pitstoptimer_exit_speed')
        self._pitstop_alert_speed = user_preferences.get_pref_int('dashboard_preferences', 'pitstoptimer_alert_speed')

    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)

    def _is_popup_open(self):
        '''
        Indicates if current popup is open
        :return True if popup is currently open
        '''
        return self._popup and self._popup._window is not None

    def _flash_pit_stop_time(self, *args):
        '''
        Flashes the final pit stop time when complete
        '''
        self.current_time = self._format_stopwatch_time() if self._flash_count % 2 == 0 else ''
        self._flash_count += 1
        if self._flash_count < self._FLASH_COUNT * 2:
            Clock.schedule_once(self._flash_pit_stop_time, self._FLASH_INTERVAL)
        else:
            self._popup.dismiss()

    def _finish_stopwatch(self):
        '''
        Finish the current stopwatch
        '''
        self._flash_count = 0
        self.ids.speed_rect.rect_color = ColorScheme.get_dark_background_translucent()
        self.exit_speed_color = ColorScheme.get_dark_background_translucent()
        self._set_exit_speed_frame_visible(False)
        Clock.schedule_once(self._flash_pit_stop_time)
        self._stop_stopwatch()

    def check_popup(self):
        '''
        Check if we should pop-up the timer
        '''
        if not self._pitstop_timer_enabled:
            return

        if self._in_race_mode():
            self._currently_racing = True
        if self.current_speed < self._pitstop_trigger_speed and\
                self._currently_racing and\
                not self._is_popup_open():
            self._start_stopwatch()

        if self.current_speed > self._pitstop_exit_speed and\
                self._is_popup_open() and\
                self._flash_count == 0:
            self._finish_stopwatch()

    def on_current_speed(self, instance, value):
        self.check_popup()

    def on_current_lap(self, instance, value):
        self.check_popup()

    def set_speed(self, value):
        self.current_speed = value

    def set_current_lap(self, value):
        self.current_lap = value

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

    def change_font_size(self):
        '''
        Auto resizes the timer widget if it spills over the edge of the bounding box
        '''
        widget = self.ids.timer
        try:
            if widget.texture_size[0] > widget.width:
                widget.font_size -= 1
        except Exception as e:
            Logger.warn('[PitstopTimerView] Failed to change font size: {}'.format(e))
コード例 #28
0
ファイル: score_board.py プロジェクト: git-vphakala/fp-kivy
class MenuButton(ButtonBehavior, Image):
    """MenuButton
    """
    def __init__(self, login_button_handler, join_game_handler, **kwargs):
        super(MenuButton, self).__init__(**kwargs)
        self.bind(on_press=self.open_modal)
        self.modal = ModalView(size_hint=(1, .6))
        self.modal_body = GridLayout(rows=2,
                                     size_hint_x=0.8,
                                     padding=[0, 20, 0, 0],
                                     spacing=5)
        self.modal.add_widget(self.modal_body)
        self.username_widget = TextInput(multiline=False,
                                         size_hint=(1, None),
                                         height="30sp")
        self.modal_body.add_widget(self.username_widget)
        self.login_button_handler = login_button_handler
        self.join_game_handler = join_game_handler
        anchor = AnchorLayout(anchor_y='top')
        self.login_button = Button(text="login", size_hint=(None, None), width="50sp",\
            height="30sp", on_press=self.onclick_login_button)
        anchor.add_widget(self.login_button)
        self.modal_body.add_widget(anchor)
        self.online_list = Label()
        self.games_list = GridLayout(cols=5)

    def open_modal(self, *args):
        """open_modal
        """
        self.modal.open()

    def close_modal(self):
        """close_modal
        """
        self.modal.dismiss()

    def onclick_login_button(self, *args):
        """onclick_login_button
        """
        username = self.username_widget.text
        if username:
            self.login_button_handler(username)

    def init_gaming(self, username):
        """init_gaming
        param username <str>
        """
        self.modal_body.clear_widgets()
        self.modal_body.rows = None
        self.modal_body.cols = 1
        self.modal_body.add_widget(Label(text="user name: " + username))
        self.modal_body.add_widget(self.online_list)
        self.modal_body.add_widget(self.games_list)

    def handle_online_list(self, online_list):
        """handle_online_list
        param online_list <list>
        """
        self.online_list.text = "Online: " + str(online_list)

    def handle_games_list(self, games_list):
        """handle_games_list
        param games_list = [[gameId, numPlayers, numPairs],[], ... ]
        """
        print("score_board.py:MenuButton.handle_games_list")
        self.games_list.clear_widgets()
        self.games_list.add_widget(Label(text="Games:", size_hint=(None, None), height="20sp",\
            width="50sp"))
        for game in games_list:
            self.games_list.add_widget(GameButton(game, self.join_game_handler,\
                size_hint=(None, None), height="20sp", width="80sp"))

    def wait_for_gaming(self, game):
        """wait_for_gaming
        param game = [gameId, numPlayers, numPairs]
        """
        set_id(game[0])
        set_num_players(game[1])
        set_num_pairs(game[2])
        set_level_time(200)
        set_in_device(False)
        self.modal_body.clear_widgets()
        self.modal_body.add_widget(
            Label(text="Waiting for the game to start."))
        self.modal_body.add_widget(
            Label(text=game[0] + ', ' + str(game[1]) + ', ' + str(game[2])))

    def render_gameover(self, game_state):
        """render_gameover
        """
        self.modal_body.clear_widgets()
        self.modal_body.add_widget(Label(text="Game over"))
        players_scores_sorted = list(
            zip(game_state["players"], game_state["scores"]))
        players_scores_sorted.sort(key=sort_by_num_player, reverse=True)
        players_ranked = []
        for i, item in enumerate(players_scores_sorted):
            player = {"name": item[0], "score": item[1]}
            player["rank"] = i + 1
            if i > 0:
                if player["score"] == players_ranked[-1]["score"]:
                    player["rank"] = players_ranked[-1]["rank"]
            players_ranked.append(player)
        game_result_table = GridLayout(cols=3)
        for player in players_ranked:
            game_result_table.add_widget(Label(text=str(player["rank"])))
            game_result_table.add_widget(Label(text=player["name"]))
            game_result_table.add_widget(Label(text=str(player["score"])))
        self.modal_body.add_widget(game_result_table)
        self.modal_body.add_widget(Button(text="Replay"))
コード例 #29
0
ファイル: main.py プロジェクト: onecore/rest-viewer-app
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
コード例 #30
0
ファイル: cpuplayer.py プロジェクト: afibanez/hexland
class CpuPlayer():

    EXACT = 0
    LOWERBOUND = -1
    UPPERBOUND = 1

    def __init__(self,cputype,**kwargs):
        self.type = cputype
        self.transtable = {}

        self.view = ModalView(size_hint=(0.4, 0.1),auto_dismiss=False)
        self.view.add_widget(SimpleModal(text="CPU Moving..."))

    @mainthread
    def showModal(self):
        self.view.open()

    @mainthread
    def hideModal(self):
        self.view.dismiss()

    # hg is hexgrid
    def move(self,hg,*largs):

        self.showModal()
        opt = {
            GAMETYPE["IA_DUMMY"]: self.mvDummy,
            GAMETYPE["IA_EASY"]: self.mvNegamax,
        }

        opt[self.type](hg)
        self.hideModal()
        return True
        

    def mvDummy(self,hg):
        time.sleep(0.5) # we need a minimum time

        sz = hg.gridsize
        possibles = list(itertools.product(range(0,sz),range(0,sz)))

        finished = False
        while not finished:
            if not len(possibles): break # sortim i passem
            
            x,y = random.choice(possibles)
            t = hg.grid[x][y]
            if t and t.content == 0:
                state = hg.getState()
                if hg.doMovement(t):
                    finished = True
                hg.loadState(state)

            if not finished:
                possibles.remove((x,y))
        else:
            # Trobat, juguem
            hg.manageTurn(t,False)
            return

        # No trobat, passem
        hg.doPass(False)

    def negamax(self,hg,ply,alpha,beta,color,player):
        alphaOrig = alpha

        # Busquem en transp table
        key = str(hg.getState())
        if key in self.transtable:
            ttentry = self.transtable[key]
            if ttentry['ply'] >= ply:
                if ttentry['flag'] == CpuPlayer.EXACT:
                    return ttentry['value'],None,None
                elif ttentry['flag'] == CpuPlayer.LOWERBOUND:
                    alpha = max(alpha,ttentry['value'])
                elif ttentry['flag'] == CpuPlayer.UPPERBOUND:
                    beta = min(beta,ttentry['value'])
                if alpha >= beta:
                    return ttentry['value'],None,None

        if ply == 0:
            score = hg.score()
            return score[player]*color,None,None

        bestValue = float('-infinity')
        bestX = None
        bestY = None
        sz = hg.gridsize
        moves = list(itertools.product(range(0,sz),range(0,sz)))
        random.shuffle(moves)

        for x,y in moves:

            doPass = False
            if x == 0 and y == 0: # Sempre es None, la fem servir com a "passar" per poder-ho integrar al bucle
                doPass = True
            else:
                t = hg.grid[x][y]
                if not t: continue

            state = deepcopy(hg.getState())
            if not doPass:
                if not hg.doMovement(t,player):
                    # Jugada invalida
                    hg.loadState(state)
                    continue
                hg.deleteGroups()

            val = -self.negamax(hg,ply-1,-beta,-alpha,-color,hg.getNextPlayerNum(player))[0]
            hg.loadState(state)

            if bestValue < val:
                bestValue = val
                bestX = x
                bestY = y

            alpha = max(alpha,val)
            if alpha >= beta:
                break # poda

        # Transposition table entry
        ttentry = {'value':bestValue,'ply':ply}
        if bestValue <= alphaOrig:
            ttentry['flag'] = CpuPlayer.EXACT
        elif bestValue >= beta:
            ttentry['flag'] = CpuPlayer.LOWERBOUND
        else:
            ttentry['flag'] = CpuPlayer.UPPERBOUND

        self.transtable[str(hg.getState())] = ttentry

        return bestValue,bestX,bestY

    def mvNegamax(self,hg):
        time.sleep(0.1) # we need a minimum time

        player = hg.player

        lliures = 0
        sz = hg.gridsize
        for x,y in list(itertools.product(range(0,sz),range(0,sz))):
            t = hg.grid[x][y]
            if t and not t.content:
                lliures += 1

        if lliures > 10:
            ply = 4
        elif lliures > 5:
            ply = 6
        else:
            ply = 8

        bestValue,x,y = self.negamax(hg,ply,float('-infinity'),float('infinity'),1,player)

        if x == 0 and y == 0:
            # Passem
            print "I pass"
            hg.doPass(False)
        else:
            # Juguem
            print "I play at",x,y
            t = hg.grid[x][y]
            hg.manageTurn(t,False)
コード例 #31
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)
コード例 #32
0
ファイル: main.py プロジェクト: Davincible/ProjectReddress
class LoginScreenClass(Screen):
    #  properties for the background texture
    texture_ = Image(source="resources/RedDress_Texture.jpg").texture
    texture_.wrap = 'repeat'
    nx = NumericProperty(0)
    ny = NumericProperty(0)

    #  other properties
    textfield_height = dp(70)
    force_refresh = False

    #  base variables for object reference
    textfield_username = ObjectProperty(None)
    textfield_password = ObjectProperty(None)
    terminal = ObjectProperty(None)
    terminal_dialog = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(LoginScreenClass, self).__init__(**kwargs)
        self.bind(size=self.update_texture_size)
        self.terminal = KivyConsole()

    def update_texture_size(self, *args):
        self.nx = float(self.width) / self.texture_.width
        self.ny = float(self.height) / self.texture_.height

    #  an event handler for when the enter button on the login screen has been pressed
    def _enter_button(self):
        username = self.textfield_username.text.strip().lower()
        password = self.textfield_password.text.strip().lower()

        if username == 'root':
            self.create_terminal_dialog()
        elif username == 'root_':
            self.force_refresh = True
            self.create_terminal_dialog()
        elif ((username == self.terminal.game_username and password == self.terminal.game_password) or (username == 'enter')) \
                and (DEBUG or self.terminal.hacked_account):
            time.sleep(.1)
            App.get_running_app().root.current = 'MainScreen'
            print("Successfully logged in")
        elif username:
            self.textfield_password.show_error(msg="Please enter a valid password")
        else:
            self.textfield_username.show_error()
            print("Username:"******"Password:", self.terminal.game_password)

    #  creates a dialog with a terminal emulator in it, and opens it
    def create_terminal_dialog(self):
        self.textfield_username.reset_textbox()
        if not self.terminal or self.force_refresh:
            self.terminal = KivyConsole()

        if not self.terminal_dialog or self.force_refresh:
            self.terminal_dialog = ModalView(size_hint=(.9, .6), pos_hint={'center_x': .5, 'center_y': .669})
            self.terminal_dialog.add_widget(self.terminal)
            self.terminal.bind(on_exit=self.terminal_dialog.dismiss)
            self.terminal.bind(on_circuitbreaker=self.start_circuitbreaker)
        self.terminal_dialog.open()
        self.terminal.focus = True

    #  dismiss the terminal dialog, and go to the CircuitBreaker game screen
    def start_circuitbreaker(self, *args):
        self.terminal_dialog.dismiss()
        # App.get_running_app().root.transition = RiseInTransition()
        App.get_running_app().root.current = 'VLSI_CircuitBreaker'
コード例 #33
0
class MDFileManager(ThemableBehavior, BoxLayout):
    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`.
    """

    save_mode = ObjectProperty(False)
    """
    Allow this to work as a save box
    """


    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`.
    """

    ext = ListProperty([])

    _window_manager = None
    _window_manager_open = False

    def __init__(self, **kwargs):
        super().__init__(orientation='vertical', **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.app = App.get_running_app()
        from kivymd.uix.button import MDFillRoundFlatButton as Button, MDRoundFlatButton

        if self.save_mode:
            action_button = MDRoundFlatButton(
                
                text="Save",
                size_hint=(1,None)
            )
            action_button.bind(on_release=self.select_directory_on_press_button)
            self.add_widget(action_button)

            from kivymd.uix.textfield import MDTextFieldRect,MDTextField
            self.saveFileName = MDTextField(text=str(self.save_mode),mode='fill', multiline=False,font_size='22sp',size_hint=(1,None))

            self.add_widget(self.saveFileName)

    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:
            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 =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,
                    }
                )
            for name in files:
                _path = os.path.join(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 != "" or not self.ext:
            if (not self.ext) or (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":
                        try:
                            if self.count_ext(content):
                                files.append(content)
                        except IndexError:
                            pass
                      
            return dirs, files
        except OSError:
            logging.exception("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):
            if not self.save_mode:
                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)
                if not self._window_manager_open:
                    return
                else:
                    self.history[0]=path
            else:
                self.history[0] = path
        else:
            try:
                self.history.pop()
                path = self.history[-1]
            except:
                logging.exception("err")
                self.close()
                self.exit_manager(1)
                return

        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."""
        if not self.save_mode:
            self.select_path(self.current_path)
        else:
            self.select_path(os.path.join( self.current_path,self.saveFileName.text))

    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 []
コード例 #34
0
class user_menu_operations():

    #This function loads the basic ui for creating,editing and deleting user data
    def users_loader(self):
        #Create three buttons and bind their respective functions to them
        self.change = MDRaisedButton(text='Change account details')
        self.change.bind(
            on_press=partial(user_menu_operations.account_changer, self))
        self.add = MDRaisedButton(text='Add New Account')
        self.add.bind(on_press=partial(user_menu_operations.new_user, self))
        self.remove = MDRaisedButton(text='Remove current user')
        self.remove.bind(on_press=partial(user_menu_operations.remover, self))
        Mainscreenvar = sm.get_screen("MainScreen")
        #add all the three buttons to the main user interface
        Mainscreenvar.ids.container.add_widget(self.change)
        Mainscreenvar.ids.container.add_widget(self.add)
        Mainscreenvar.ids.container.add_widget(self.remove)

    #This function displays the popup for changing details of an user
    def account_changer(self, caller):
        self.popup_card = MDCard(
            size=(400, 400),
            size_hint=(None, None),
            md_bg_color=(0.1, 0.1, 0.1, 1),
            radius=(20, 20, 20, 20),
        )

        self.layout = ModalView(
            size=(500, 500),
            size_hint=(None, None),
            background_color=(0, 0, 0, .9),
            background='atlas://data/images/defaulttheme/action_item')
        self.layout.add_widget(self.popup_card)
        #Create an object that holds the main ui using the template User_details
        self.user_details = User_Details()
        #set the current logged in user's username and password
        self.user_details.ids.user_name.text = current_user
        self.user_details.ids.password.text = current_password
        #bind the save function to the save button from the ui
        self.user_details.ids.save.bind(
            on_press=partial(user_menu_operations.saver, self, 1))
        self.popup_card.add_widget(self.user_details)
        #dispay the popup
        self.layout.open()

    #This function displays a popup that allows the user to create a new user account
    def new_user(self, caller):
        self.popup_card = MDCard(
            size=(400, 400),
            size_hint=(None, None),
            md_bg_color=(0.1, 0.1, 0.1, 1),
            radius=(20, 20, 20, 20),
        )

        self.layout = ModalView(
            size=(500, 500),
            size_hint=(None, None),
            background_color=(0, 0, 0, .9),
            background='atlas://data/images/defaulttheme/action_item')
        self.layout.add_widget(self.popup_card)
        self.user_details = User_Details()
        self.user_details.ids.save.bind(
            on_press=partial(user_menu_operations.saver, self, 2))
        self.popup_card.add_widget(self.user_details)
        self.layout.open()

    #This function saves any changes and any new user account details
    def saver(self, op_id, caller):
        data = (caller.parent.ids.user_name.text,
                caller.parent.ids.password.text)
        #if we are updating data we delete data that is already inside the table
        if op_id == 1:
            mycursor.execute("DELETE FROM users WHERE user_id = %s",
                             (current_user, ))
            mydb.commit()
        #we insert new values into the table
        mycursor.execute("INSERT INTO users VALUES(%s,%s)", data)
        mydb.commit()
        if op_id == 1:
            #if we are updating existing details we rename the table of notes with new user name
            mycursor.execute("ALTER TABLE " + current_user + " RENAME TO " +
                             caller.parent.ids.user_name.text)
            #clear the widgets on screen
            sm.get_screen("MainScreen").ids.container.clear_widgets()
            #reset the screen to the login screen
            sm.current = ('LoginScreen')

        else:
            #if new user is being added we create a new table in their name
            mycursor.execute(
                "CREATE TABLE " + caller.parent.ids.user_name.text +
                "(id double, content text, date date, color int(2))")
        #close the popup window
        self.layout.dismiss()

    #This function is called when the current user account has to be deleted
    def remover(self, caller):
        #First we delete the user name from the user table
        mycursor.execute("DELETE FROM users WHERE user_id = %s",
                         (current_user, ))
        mydb.commit()
        #Then we drop the table that stores all the users sticky notes
        mycursor.execute("DROP TABLE " + current_user)
        #clear screen
        sm.get_screen("MainScreen").ids.container.clear_widgets()
        #reset to login screen
        sm.current = 'LoginScreen'
コード例 #35
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
コード例 #36
0
ファイル: filemanager.py プロジェクト: jaypatel2103/Pdf-APP
class MDFileManager(ThemableBehavior, MDFloatLayout):
    list_of_selected_images_or_pdfs = []
    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", "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`.
    """

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

    :attr:`preview` 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.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 = self.ext + [".png", ".jpg", ".jpeg"]

    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)
        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.preview:
            for name_dir in 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),
                    }
                )
            for name_file in files:
                name_file = name_file.replace("\\", "/")
                file_name = name_file.split("/")
                file_name = file_name[-1]

                if os.path.splitext(name_file)[1] in self.ext:
                    manager_list.append(
                        {
                            "viewclass": "BodyManagerWithPreviewForFiles",
                            "path": name_file,
                            "name": file_name,
                            "realpath": os.path.join(path),
                            "type": "files",
                            "events_callback": self.select_file,
                            "height": dp(150),
                        }
                    )
        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:
                file_name = name.replace("\\", "/")
                file_name = file_name.split("/")
                file_name = file_name[-1]
                _path = path + file_name if path == "/" else path + "/" + file_name
                if self.ext and os.path.splitext(name)[1] in self.ext:
                    manager_list.append(
                        {
                            "viewclass": "BodyManager",
                            "path": _path,
                            "icon": "file-outline",
                            "dir_or_file_name": file_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 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:
                                files.append(os.path.join(path, 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."""

        self.current_path = path
        # BodyManagerWithPreviewForFiles.clear_on_next_dir(BodyManagerWithPreviewForFiles())
        self.list_of_selected_images_or_pdfs = []
        self.show(path)

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

        if checkbox is True:
            self.list_of_selected_images_or_pdfs.append(path)
        else:
            try:
                self.list_of_selected_images_or_pdfs.remove(path)
            except:
                print('error')

    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.exit_manager(self.list_of_selected_images_or_pdfs,"selection_done",)