예제 #1
2
class ImagesMenu(BaseScreen):
    def __init__(self, name, *navigate_screens):
        super(ImagesMenu, self).__init__(name, *navigate_screens)
        self.lower_grid = BoxLayout(orientation='vertical',
                                    spacing=5,
                                    padding=5)
        self.lower_panel.add_widget(self.lower_grid)

        self.filechooser = FileChooserListView()
        if platform == 'android':
            self.filechooser.path = '/sdcard/DCIM'
        else:
            self.filechooser.path = os.getcwd()
        self.filechooser.bind(
            on_selection=lambda x: self.selected(self.filechooser.selection))

        self.open_file_button = MDRaisedButton(text='Upload Image',
                                               size_hint=(1, .1))
        self.open_file_button.bind(on_release=lambda x: self.open_f(
            self.filechooser.path, self.filechooser.selection))

        self.lower_grid.add_widget(
            TextInput(size_hint=(1, .12), text='Image name'))
        self.lower_grid.add_widget(self.open_file_button)
        self.lower_grid.add_widget(self.filechooser)

    def open_f(self, path, filename):
        if not filename:
            img_file = None
            image_pop = Popup()
            image_pop.add_widget(
                MDLabel(text='No image file selected', halign='center'))
            image_pop.open()
        else:
            img_file = os.path.join(path, filename[0])
        image_pop = Popup()
        image_pop.add_widget(Image(source=img_file))
        image_pop.open() if img_file else ''

    def open_image_screen_callback(self):
        self.upper_panel.navigate_next()
예제 #2
0
 def init_selector(self, _height):
     # Use a FileChooserListView for selector
     _selector = FileChooserListView()
     _selector.height = _height
     _selector.dirselect = True
     _selector.bind(selection = self.set_selector_text)
     return _selector
예제 #3
0
    def create_open_file_dialog(self):
        chooser = BoxLayout()
        container = BoxLayout(orientation='vertical')

        def open_file(path, filename):
            try:
                filepath = os.path.join(path, filename[0])
                self.__open_filename = filepath
                self.open_file_dialog_to_report_selector()
            except IndexError:
                self.error_message("Please pick an appendix (.csv) file")

        filechooser = FileChooserListView()
        filechooser.path = os.path.expanduser("~")
        filechooser.bind(on_selection=lambda x: filechooser.selection)
        filechooser.filters = ["*.csv"]

        open_btn = Button(text='open', size_hint=(.2,.1), pos_hint={'center_x': 0.5, 'center_y': 0.5})
        open_btn.bind(on_release=lambda x: open_file(filechooser.path, filechooser.selection))

        container.add_widget(filechooser)
        container.add_widget(open_btn)
        chooser.add_widget(container)

        file_chooser = Popup(title='Open file',
        content=chooser,
        size_hint=(.9, .7 ), pos_hint={'center_x': 0.5, 'center_y': 0.5})

        return file_chooser 
예제 #4
0
def file_dialog(title=None, path='.', filter='files', events_callback=None,
                size=None):
    def is_dir(directory, filename):
        return os.path.isdir(os.path.join(directory, filename))

    def is_file(directory, filename):
        return os.path.isfile(os.path.join(directory, filename))

    if not size:
        size = (.7, .5)

    file_manager = FileChooserListView(path=path, filters=['\ *.png'])
    if isinstance(events_callback, types.FunctionType) or \
        isinstance(events_callback, types.MethodType):
        file_manager.ids.layout.ids.button_ok.bind(
            on_release=lambda x: events_callback(file_manager.path))
        file_manager.bind(selection=lambda *x: events_callback(x[1:][0][0]))

    if filter == 'folders':
        file_manager.filters = [is_dir]
    elif filter == 'files':
        file_manager.filters = [is_file]

    dialog = card(file_manager, title, size=size)
    return dialog, file_manager
예제 #5
0
class KeyFile(GridLayout, Screen):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.current_file = None
        self.last_path = None
        if platform == 'android':
            self.last_path = '/storage/emulated/0'
            from android.permissions import request_permissions, Permission
            request_permissions([Permission.READ_EXTERNAL_STORAGE])
        self.cols = 1
        self.size_hint_x = 1
        self.padding = (70, 0)
        self.row_force_default = True
        self.row_default_height = 60
        self.add_widget(Menu(for_screen='key'))
        self.add_widget(Label(text='Use any file as password source', size_hint=(1, None), height=60))
        row = GridLayout(
            cols=2,
            row_force_default=True,
            row_default_height=60
        )
        row.add_widget(Label(text='Alphanumeric only:'))
        self.alnum = CheckBox(size_hint=(None, None), width=40, height=40)
        row.add_widget(self.alnum)
        self.add_widget(row)
        self.selectFile = Button(text='Select file', size_hint=(1, None), height=40)
        self.selectFile.bind(on_press=self.btn_select_file)
        self.add_widget(self.selectFile)
        self.chooser = None
        
    def btn_select_file(self, btn):
        ## Create popup
        if self.last_path:
            self.fileChooser = FileChooserListView(path=self.last_path)
        else:
            self.fileChooser = FileChooserListView()
        self.fileChooser.bind(on_touch_up=self.on_file_select)
        if self.chooser == None:
            self.chooser = Popup(title='Select file',
                size_hint=(None, None), size=(Window.width-50, Window.height-100),
                #content=self.fileChooser
            )
        self.chooser.content = self.fileChooser
        ## Show popup
        self.chooser.open()
    
    def on_file_select(self, *args, **kwargs):
        if len(self.fileChooser.selection) > 0:
            if self.current_file == self.fileChooser.selection[0]:
                self.current_file = None
            else:
                self.current_file = self.fileChooser.selection[0]
                if self.current_file:
                    self.chooser.dismiss()
                    self.last_path = self.fileChooser.path
                    del(self.fileChooser)
                    del(self.chooser)
                    self.chooser = None
                    main.gen_from_file(self.current_file)
예제 #6
0
 def __init__(self, textinput):
     self.textinput = textinput
     chooser = FileChooserListView()
     chooser.bind(selection=self.select)
     super(Browser_Popup, self).__init__(title='Choosing File',
                                         content=chooser,
                                         size_hint=(None, None),
                                         height=(500), width=(350))
예제 #7
0
 def show_file_explorer(self):
     popup = Popup(size_hint=(0.8, 0.8))
     file_explorer = FileChooserListView(
         filters=['*.jpg', '*.png', '*.jpeg'])
     file_explorer.bind(on_submit=self.show_add_slide)
     file_explorer.popup = popup
     popup.content = file_explorer
     popup.title = _('File explorer')
     popup.open()
예제 #8
0
def ImportFilesPopup(x=None):
    layout = BoxLayout(orientation='vertical')

    hlp = Label(text="""Choose a directory to sync with.
     All files in the directory will be imported, 
     (dir/foo.txt will map to foo.txt, and all files in the stream that
     are not in the folder will be deleted from the stream.
     
     Include an index.html to create a website.
     """)
    fch = FileChooserListView()
    fch.path = os.getcwd()
    fch.dirselect = True
    filename = TextInput(hint_text="Foldername",
                         multiline=False,
                         size_hint=(1, 0.1))

    button = Button(text='Select', font_size=14, size_hint=(1, 0.1))

    def s(x, y):
        try:
            filename.text = os.path.basename(str(fch.selection[0]))
        except:
            filename.text = ''

    fch.bind(selection=s)
    n = []

    def f(j):
        try:
            fn = os.path.join(fch.path, filename.text)
            if fn:
                if os.path.isdir(fn):
                    db.importFiles(fn, True)
                else:
                    presentError("Not a directory")
            else:
                presentError("Nothing selected!s")
        except:
            presentError(traceback.format_exc())
        popup.dismiss()

    layout.add_widget(hlp)
    layout.add_widget(fch)
    layout.add_widget(filename)

    layout.add_widget(button)

    popup = Popup(title='Open or Create a Stream',
                  content=layout,
                  size_hint=(None, None),
                  size=(600, 400))

    button.bind(on_press=f)

    popup.open()
예제 #9
0
class FileDialog(FloatLayout):
    path = ObjectProperty(None)
    file = ObjectProperty(None)
    def __init__(self, **kwargs):
        self.mode = kwargs.get('mode')
        super(FileDialog, self).__init__(**kwargs)
        self.register_event_type('on_cancel')
        self.register_event_type('on_submit')
        vbox = self.vbox = BoxLayout(orientation='vertical')
        self.add_widget(vbox)
        self.chooser = FileChooserListView(path=self.path)
        vbox.add_widget(self.chooser)
        self.text_input = TextInput(size_hint_y=None, height=30, multiline=False)
        if self.file:
            self.text_input.text = self.file
        vbox.add_widget(self.text_input)
        hbox = BoxLayout(size_hint_y=None, height=30)
        vbox.add_widget(hbox)
        self.cancel_btn = Button(text='Cancel')
        hbox.add_widget(self.cancel_btn)
        self.confirm_btn = Button(text=self.mode.title())
        hbox.add_widget(self.confirm_btn)
        self.text_input.bind(text=self.on_text_input_text)
        self.chooser.bind(path=self.on_chooser_path, 
                          selection=self.on_chooser_selection, 
                          on_submit=self.on_chooser_submit)
        self.cancel_btn.bind(on_release=self.on_cancel_btn_release)
        self.confirm_btn.bind(on_release=self.on_confirm_btn_release)
    def do_layout(self, *args):
        if self.parent is not None:
            self.pos = self.parent.pos
            self.size = self.parent.size
            self.vbox.pos = self.parent.pos
            self.vbox.size = self.parent.size
        super(FileDialog, self).do_layout(*args)
    def on_text_input_text(self, instance, value):
        if not self.text_input.focus:
            return
        self.file = value
    def on_chooser_path(self, instance, value):
        self.path = value
    def on_chooser_selection(self, instance, value):
        self.file = value[0]
        self.text_input.text = self.file
    def on_chooser_submit(self, *args):
        self.dispatch('on_submit')
    def on_cancel_btn_release(self, *args):
        self.dispatch('on_cancel')
    def on_confirm_btn_release(self, *args):
        if self.file:
            self.dispatch('on_submit')
    def on_cancel(self, *args):
        pass
    def on_submit(self, *args):
        pass
예제 #10
0
def FilePopup(x):
    layout = BoxLayout(orientation='vertical')

    fch = FileChooserListView()
    fch.path = os.getcwd()

    pubkey = TextInput(
        hint_text=
        "Public Key of the stream, leave blank to create new stream or accept the one in the file",
        multiline=False,
        size_hint=(1, 0.1))
    filename = TextInput(hint_text="Filename",
                         multiline=False,
                         size_hint=(1, 0.1))

    button = Button(text='Select', font_size=14, size_hint=(1, 0.1))

    def s(x, y):
        try:
            filename.text = os.path.basename(str(fch.selection[0]))
        except:
            filename.text = ''

    fch.bind(selection=s)
    n = []

    def f(j):
        try:
            if filename.text:
                openStream(os.path.join(fch.path, filename.text), pubkey.text)
                n.extend(fch.selection)
            else:
                presentError("Nothing selected!s")
        except:
            presentError(traceback.format_exc())
        popup.dismiss()

    layout.add_widget(pubkey)
    layout.add_widget(fch)
    layout.add_widget(filename)

    layout.add_widget(button)

    popup = Popup(title='Open or Create a Stream',
                  content=layout,
                  size_hint=(None, None),
                  size=(600, 400))

    button.bind(on_press=f)

    popup.open()
예제 #11
0
    def __init__(self, **kwargs):
        super(myLayout, self).__init__(**kwargs)
        self.sound = None

        layout = BoxLayout(pos=self.pos, size=self.size, spacing=10)

        self.add_widget(layout)

        flc = FileChooserListView(path='/home/edward/Music',
                                  filters=['*.mp3'],
                                  size=(7, 3))
        flc.bind(selection=self.load_sound)  # bind to the property `selection`

        layout.add_widget(flc)

        # creating the play button

        play = Button(text="PLAY",
                      valign='center',
                      halign='center',
                      background_color=blue,
                      size_hint=(0.3, 0.5))

        play.bind(on_press=self.play_pressed)
        layout.add_widget(play)

        # creating the stop button

        stop = Button(text="STOP",
                      valign='center',
                      halign='center',
                      size_hint=(0.3, 0.6),
                      background_color=red)
        layout.add_widget(stop)
        stop.bind(on_press=self.stop_pressed)

        #creating a Label

        display = Label(text="kiwiAudioPlayer", halign='right', size=(3, 5))

        layout.add_widget(display)

        #displaying an animated image

        animate = AsyncImage(source='https://i.gifer.com/KNGq.gif',
                             allow_stretch=False,
                             anim_delay=0.10)

        layout.add_widget(animate)
예제 #12
0
    def tileset_popup(self, *args):
        if self.wang_tiles_map:
            self.wang_tiles_map.disable_user_interaction()

        popup_content = BoxLayout(orientation='vertical')
        file_chooser = FileChooserListView(
            filters=['*.pickle'],
            rootpath=os.path.dirname(os.path.realpath(__file__)) + "/data")
        file_chooser.bind(on_submit=self.selected_tileset)
        # file_chooser.bind(on_submit=self.dismiss_popup)

        popup_content.add_widget(file_chooser)
        popup = TilesetChooser(content=popup_content)
        popup.bind(on_dismiss=self.wang_tiles_map.enable_user_interaction)
        popup.open()
예제 #13
0
    def __init__(self, **kwargs):
        super(ScreenThree, self).__init__(**kwargs)
        container = BoxLayout(orientation='vertical')

        filechooser = FileChooserListView()
        filechooser.bind(
            on_selection=lambda x: self.selected(filechooser.selection))

        open_btn = Button(text='Open and predict!',
                          font_size='30sp',
                          size_hint=(1, .2))
        open_btn.bind(on_release=lambda x: self.open(filechooser.selection))

        container.add_widget(filechooser)
        container.add_widget(open_btn)
        self.add_widget(container)
예제 #14
0
    def __init__(self, **kwargs):
        super(FileChooserPopup, self).__init__(**kwargs)

        self.title = 'Select features file'

        layout = RelativeLayout()

        file_chooser_list_view = FileChooserListView(filters=['*.txt', '*.data'], size_hint=(1, 0.8), pos_hint={'x': 0, 'y': 0.2})
        file_chooser_list_view.bind(selection=self.file_chooser_selection_do)
        self.text_input = TextInput(text='', readonly=True, size_hint=(1, 0.1), pos_hint={'x': 0, 'y': 0.1})

        layout.add_widget(file_chooser_list_view)
        layout.add_widget(self.text_input)
        layout.add_widget(Button(text='Select', italic=True, on_release=self.dismiss, size_hint=(0.25, 0.1), pos_hint={'x': 0.25, 'y': 0}))
        layout.add_widget(Button(text='Cancel', italic=True, on_release=self.cancel_btn_do, size_hint=(0.25, 0.1), pos_hint={'x': 0.5, 'y': 0}))

        self.content = layout
예제 #15
0
    def open_pop_up(self, button):
        layout = BoxLayout(orientation='vertical')
        # open button
        filechooser = FileChooserListView(path=os.getcwd())
        filechooser.bind(on_selection=lambda x: self.selected(filechooser.selection))
        popup_menubar = GridLayout(cols=2, size_hint=(1,None))

        open_btn = Button(text='open', size_hint=(0.5, None))
        open_btn.bind(on_release=lambda x: self.open(filechooser.path, filechooser.selection))
        self.popup = Popup(title='Demo Popup',
                      content=layout)
        self.popup.open()
        closebtn = Button(text='close', on_press=self.close, size_hint=(0.5, None))

        popup_menubar.add_widget(open_btn)
        popup_menubar.add_widget(closebtn)
        layout.add_widget(filechooser)
        layout.add_widget(popup_menubar)
예제 #16
0
    def __init__(self, **kwargs):
        print("In FileBrowser")
        super(FileBrowser, self).__init__(**kwargs)
        self.app = MDApp.get_running_app()
        self.Browser = Popup(size_hint=(0.75, 0.75))
        fc = FileChooserListView()
        fc.rootpath = os.environ["PULSO_APP_ROOT"]
        exit = Button(text='Cancel',
                      size_hint=(1, 0.1),
                      on_release=self.Browser.dismiss)
        layout = BoxLayout(orientation='vertical')
        layout.add_widget(fc)
        layout.add_widget(exit)
        self.Browser.add_widget(layout)

        fc.bind(selection=lambda instance, x: self.set_select(x))
        self.picker_btn.bind(
            on_release=lambda x: self.Browser.open(self.Browser))
예제 #17
0
 def __init__(self, open_callback, popuptitle):
     self.m_fctOpenCallback = open_callback
     layout = BoxLayout(orientation="vertical")
     self.selection = TextInput(multiline=False,text=os.getcwd() + os.sep,
         readonly=False,size_hint=(1,0.1),focus=True)
     layout.add_widget(self.selection)
     filechooser = FileChooserListView(filters=["*.py","*.txt"],path=os.getcwd())
     layout.add_widget(filechooser)
     filechooser.bind(selection = self.on_selection)
     buttonslayout = BoxLayout(size_hint=(1, 0.1),orientation="horizontal")
     btn1 = Button(text='OK', size_hint=(0.5, 1))
     btn1.bind(on_release = self.on_ok_button)
     buttonslayout.add_widget(btn1)
     btn2 = Button(text='Cancel', size_hint=(0.5, 1))
     btn2.bind(on_release = self.on_cancel_button)
     buttonslayout.add_widget(btn2)
     layout.add_widget(buttonslayout)
     self.popup = Popup(title=popuptitle,content=layout,size_hint=(1,1))
     self.popup.open()
예제 #18
0
class FileExplorer(BoxLayout):
    def __init__(self, **kwargs):
        super(FileExplorer, self).__init__(**kwargs)

        self.orientation = 'vertical'
        self.fichoo = FileChooserListView(size_hint_y=0.8, path='./')
        self.fichoo.dirselect = True
        self.add_widget(self.fichoo)
        self.update_lbl_filename = ''

        control = GridLayout(cols=5,
                             row_force_default=True,
                             row_default_height=35,
                             size_hint_y=0.14,
                             padding=[10, 10])
        lbl_dir = Label(text='Folder', size_hint_x=None, width=150)
        self.tein_dir = TextInput(size_hint_x=None, width=400)
        bt_dir = Button(text='Select file', size_hint_x=None, width=80)
        bt_dir.bind(on_release=self.on_button_select)

        self.fichoo.bind(selection=self.on_mouse_select)

        control.add_widget(lbl_dir)
        control.add_widget(self.tein_dir)
        control.add_widget(bt_dir)

        self.add_widget(control)
        return

    def on_button_select(self, instance):
        self.update_lbl_filename = os.path.join(self.fichoo.path,
                                                self.fichoo.selection[0])
        self.parent.parent.parent.dismiss()
        return

    def on_mouse_select(self, obj, val):
        self.tein_dir.text = str(self.fichoo.path)
        return

    def on_touch_up(self, touch):
        if self.fichoo.selection:
            self.tein_dir.text = str(self.fichoo.selection[0])
        return super().on_touch_up(touch)
예제 #19
0
    def __init__(self, load_callback, **kwargs):
        self.load_callback = load_callback
        super(FileChooserWindow, self).__init__(**kwargs)
        self.layout = RelativeLayout()

        fc = FileChooserListView(filters=["*.csv", "*.xlsx", "*.txt"],
                                 size_hint=(.8, 1))
        fc.bind(on_submit=self.file_chosen)
        self.layout.add_widget(fc)

        exit_btn = Button(text='Exit',
                          size_hint=(.1, .1),
                          pos_hint={
                              'center_x': .9,
                              'center_y': .9
                          })
        exit_btn.bind(on_press=self.dismiss)
        self.layout.add_widget(exit_btn)

        self.add_widget(self.layout)
예제 #20
0
    def __init__(self, **kvargs):
        super(FileChooser, self).__init__(**kvargs)

        box = BoxLayout(orientation="vertical", spacing=10)
        filechooser = FileChooserListView()
        filechooser.bind(selection=self.select_callback)
        box.add_widget(filechooser)

        if self.filter == "folder":
            box.add_widget(SettingSpacer())
            box.add_widget(Button(text=self.text_button_select,
                                  size_hint=(1, .1),
                                  on_press=self.select_callback))
            filechooser.filters = [self.is_dir]
        elif self.filter == "files":
            filechooser.filters = [self.is_file]

        self.body = Popup(title=self.title, content=box, size_hint=self.size,
                          auto_dismiss=self.auto_dismiss,
                          background=self.background_image)
        self.body.bind(on_dismiss=self.dismiss_callback)
        self.body.open()
예제 #21
0
파일: fdialog.py 프로젝트: HeaTTheatR/Easy
    def __init__(self, **kvargs):
        super(FDialog, self).__init__(**kvargs)

        box = BoxLayout(orientation='vertical', spacing=10)
        fdialog = FileChooserListView(path=self.path)
        fdialog.bind(selection=self.events_callback)
        box.add_widget(fdialog)

        if self.filter == 'folder':
            box.add_widget(SettingSpacer())
            box.add_widget(
                Button(text=self.text_button_ok, size_hint=(1, .1),
                       background_normal=self.background_image_buttons[0],
                       background_down=self.background_image_shadows[0],
                       on_press=self.events_callback)
            )
            fdialog.filters = [self.is_dir]
        elif self.filter == 'files':
            fdialog.filters = [self.is_file]

        self.content = box
        self.open()
예제 #22
0
    def __init__(self, **kvargs):
        super(FDialog, self).__init__(**kvargs)

        box = BoxLayout(orientation='vertical', spacing=10)
        fdialog = FileChooserListView(path=self.path)
        fdialog.bind(selection=self.events_callback)
        box.add_widget(fdialog)

        if self.filter == 'folder':
            box.add_widget(SettingSpacer())
            box.add_widget(
                Button(text=self.text_button_ok,
                       size_hint=(1, .1),
                       background_normal=self.background_image_buttons[0],
                       background_down=self.background_image_shadows[0],
                       on_press=self.events_callback))
            fdialog.filters = [self.is_dir]
        elif self.filter == 'files':
            fdialog.filters = [self.is_file]

        self.content = box
        self.open()
예제 #23
0
파일: main.py 프로젝트: Taiwar/BuRn_v2
    def build(self):
        # Datei/Ordner-Auswahl-Widget
        file_chooser = FileChooserListView(size_hint_y=1)
        file_chooser.dirselect = True
        file_chooser.multiselect = False
        file_chooser.filter = ["*.-----"]  # Nonsens-Dateiendung um nur Ordner anzuzeigen
        file_chooser.bind(selection=lambda _, x: self.on_select(file_chooser.selection))
        file_chooser.size_hint_min_y = 400

        # Auswahlknopf
        select_button = Button(text="Auswählen", size_hint=(1, .2))
        select_button.bind(on_release=lambda x: self.on_submit())

        # Container für Knopf und Ordnerauswahl
        container = BoxLayout(orientation="vertical")
        container.add_widget(file_chooser)
        container.add_widget(Padding(select_button, 200, 5))

        # Screens
        self.browser_screen.add_widget(container)
        self.main_screen.add_widget(BuRnScreen(switch_dirs=self.switch_dirs, run_process=self.run_process))

        self.sm.switch_to(self.browser_screen)  # Anfangsbildschirm ist die Ordnerauswahl
        return self.sm  # ScreenManager ist "root" der Oberfläche
예제 #24
0
파일: main.py 프로젝트: btrent/qflash
    def build(self):
        if (not self.is_desktop()):
            Config.set('postproc', 'retain_time', '10')
            Config.set('postproc', 'double_tap_time', '1')
            Config.set('postproc', 'triple_tap_time', '2')
            Config.set('graphics', 'fullscreen', 'auto')
            Config.write()

        ##################################

        platform = kivy.utils.platform()

        ##################################
        # Start screen
        ##################################
        start_screen = Screen(name='start')
        start_screen.bind(on_pre_enter=self.generate_start_screen)
        
        ##################################
        # Card screen
        ##################################
        card_layout = BoxLayout(orientation='vertical',size_hint=(1,.95))
        card_widget = BoxLayout(size_hint=(1,.85))
        card_buttons_widget = BoxLayout(size_hint=(1,.15))

        self.card_label = Label(markup=True, pos=(0,0), font_name='img/ipag.ttf',
                                font_size=64, halign="center", valign="top")
        self.card_label.bind(on_touch_down=self.on_card_press)
        card_widget.add_widget(self.card_label)

        again_btn = Button(markeup=True)
        again_btn.text = "again"
        again_btn.bind(on_press=self.process_card_btn)
        card_buttons_widget.add_widget(again_btn)

        soon_btn = Button(markeup=True)
        soon_btn.text = "soon"
        soon_btn.bind(on_press=self.process_card_btn)
        card_buttons_widget.add_widget(soon_btn)

        later_btn = Button(markeup=True)
        later_btn.text = "later"
        later_btn.bind(on_press=self.process_card_btn)
        card_buttons_widget.add_widget(later_btn)

        never_btn = Button(markeup=True)
        never_btn.text = "never"
        never_btn.bind(on_press=self.process_card_btn)
        card_buttons_widget.add_widget(never_btn)

        card_layout.add_widget(card_widget)
        card_layout.add_widget(card_buttons_widget)

        card_screen = Screen(name='main')
        card_screen.add_widget(card_layout)
        card_screen.bind(on_enter=self.card_refresh)

        ##################################
        # Settings screen
        ##################################
        settings_screen = SettingsScreen(name='settings')
        settings_screen.add_widget(self.generate_settings())

        ##################################
        # No more cards screen
        ##################################

        no_more_layout = BoxLayout(size_hint=(1,1), orientation='vertical')
        no_more_label = Label(markup=True, pos=(0,0), font_name='img/ipag.ttf', size_hint=(1,.85),
                              font_size=64, halign="center", text="No more cards to review.")
        no_more_layout.add_widget(no_more_label)
        no_more_btn_layout = BoxLayout(size_hint=(1,.15))

        no_more_home_btn = Button(markup=True)
        no_more_home_btn.text = "Home"
        no_more_home_btn.bind(on_press=self.go_to_start_screen)
        no_more_btn_layout.add_widget(no_more_home_btn)

        no_more_exit_btn = Button(markup=True)
        no_more_exit_btn.text = "Done"
        no_more_exit_btn.bind(on_press=sys.exit)
        no_more_btn_layout.add_widget(no_more_exit_btn)

        no_more_layout.add_widget(no_more_btn_layout)

        no_more_screen = Screen(name='finished')
        no_more_screen.add_widget(no_more_layout)

        import_layout = BoxLayout(size_hint=(1,1), orientation='vertical')
        self.import_msg_label = Label(markup=True, pos=(0,0), font_name = 'img/ipag.ttf', size_hint=(1,.1),
                                      font_size=24, halign='left', text='Please select a .tsv file.')
        import_layout.add_widget(self.import_msg_label)        

        #TODO P3: Can we increase text size?
        import_file_chooser = FileChooserListView(on_submit=self.import_list, path='/')
        import_file_chooser.bind(selection=self.import_list)
        import_layout.add_widget(import_file_chooser)

        import_cancel_button = Button(text="Cancel", on_press=self.go_to_start_screen, size_hint=(1,.15))
        import_layout.add_widget(import_cancel_button)

        import_screen = Screen(name='import')
        import_screen.add_widget(import_layout)

        # Add screens
        # sm = ScreenManager(transition=SlideTransition())
        sm = ScreenManager(transition=FadeTransition())
        sm.add_widget(start_screen)
        sm.add_widget(card_screen)
        sm.add_widget(settings_screen)
        sm.add_widget(no_more_screen)
        sm.add_widget(import_screen)

        self.on_load(1)

        return sm
예제 #25
0
class NukeBoxApp(App, KivyMP3):
    '''
	This is the main application class for the NukeBox 2000 mobile application.
	-	This inherits the Kivys main app class and a custom KivyMP3 class which
		provides a simpler way to view and interact with MP3's on a device.
	'''
    connection = None

    # Built in Kivy Method
    def build(self):
        '''
		Build method is required by Kivy, it returns the main widget to the window.
		'''

        # Assign the setup method
        root = self.setup_gui()

        #Return the Window built inside setup_gui
        return root

    # Define the setup method.
    def setup_gui(self):
        '''
		The setup method is used to essentially build the applications.
		-	Widgets are created and assigned to containers.
		-	Layering of containers provides additional functionality such as the
			spring feature when dragging down on the file browser
		'''

        # Check the operating system and set the file directory prefix.

        # System is Linux
        if platform == "linux":
            self.prefix = "sdcard/"
            # set the window size to a mobile ratio
            Window.size = (432, 768)

        # System is Android
        else:
            self.prefix = "/sdcard/"

        # Get the MAC Address in hex format.
        self.mac = hex(get_mac())

        # Create the main wrapper
        self.wrap = GridLayout(cols=1, rows=4)

        # Create the Carosel
        self.carousel = Carousel(direction='right',
                                 size_hint=(1, .7),
                                 loop="True",
                                 anim_move_duration=(.1),
                                 anim_cancel_duration=(.1),
                                 min_move=(.1),
                                 scroll_distance=("20dp"),
                                 scroll_timeout=(100))

        # Carosel One - Downloads Folder
        self.slideOne = BoxLayout(orientation="vertical", size_hint=(1, 1))
        self.browserOne = KivyMP3.MyID3(self, str(self.prefix) + "Download/")
        self.slideOne.add_widget(self.browserOne)
        self.carousel.add_widget(self.slideOne)

        # Carosel Two - Music Folder
        self.browserTwo = KivyMP3.MyID3(self, str(self.prefix) + "Music/")
        self.slideTwo = BoxLayout(orientation="vertical")
        self.carousel.add_widget(self.slideTwo)
        self.slideTwo.add_widget(self.browserTwo)

        # Create Header Image
        header = BoxLayout(orientation="vertical", size_hint=(1, .1))
        headerImage = Button(background_normal="./images/header.png",
                             background_down="./images/header.png",
                             size_hint=(1, 1))
        header.add_widget(headerImage)

        # Create Header Buttons - (These Emlulate Tab Buttons)
        headerBtns = BoxLayout(orientation="horizontal", size_hint=(1, .1))
        headerBtnOne = Button(text="Downloads",
                              size_hint=(.5, 1),
                              background_normal='images/tabone.png',
                              background_down='images/tabtwo.png')
        headerBtnTwo = Button(text="Music",
                              size_hint=(.5, 1),
                              background_normal='images/tabone.png',
                              background_down='images/tabtwo.png')
        headerBtns.add_widget(headerBtnOne)
        headerBtns.add_widget(headerBtnTwo)

        # Button Box

        # Anchor to bottom of screen
        self.ButtonAnchorLayout = AnchorLayout(anchor_x='center',
                                               anchor_y='bottom',
                                               size_hint=(1, .1))

        # Footer
        self.ButtonLayout = BoxLayout(orientation="horizontal",
                                      size_hint=(1, 1))
        self.btn = Button(background_normal="./images/footer.png",
                          background_down="./images/footer.png",
                          size_hint=(1, 1))
        # Footer layout
        self.ButtonLayout.add_widget(self.btn)
        self.ButtonAnchorLayout.add_widget(self.ButtonLayout)

        # File Browser / Selection

        # While the KivyMP3 file overwrites this functionality I decided to
        # 	leave it within the file as a third slide to provde access to
        # 	non-traditional folders.

        # Call the file browser - set the default path to the root and only view MP3s
        self.fileBrowse = FileChooserListView(rootpath="/", filters=["*.mp3"])
        self.carousel.add_widget(self.fileBrowse)
        self.fileBrowse.bind(on_submit=self.fileSelect)

        # Add Items to main
        self.wrap.add_widget(header)
        self.wrap.add_widget(headerBtns)

        # Add Carosel to Grid Layout
        self.wrap.add_widget(self.carousel)
        self.wrap.add_widget(self.ButtonAnchorLayout)

        # Assign events to methods
        headerBtnOne.bind(on_press=partial(self.swTab, 0))
        headerBtnTwo.bind(on_press=partial(self.swTab, 1))

        # Return the newly created window
        return self.wrap

    #=======================#
    #		Methods			#
    #=======================#

    # Song selection method
    def songSelect(self, instance):
        '''
		This builds upon the KivyMP3 method, introducing some custom
		specifically for this application. The method takes the instance
		value by default:
		-	Instance value of the button being pressed.
		'''

        if self.carousel.index == 0:
            fileDir = str(self.prefix) + "Download/" + str(
                instance.musicFileName)
        elif self.carousel.index == 1:
            fileDir = str(self.prefix) + "Music/" + str(instance.musicFileName)

        # Call the Twisted network transfer method
        self.twistIt(fileDir)

    # Switch tabs
    def swTab(self, slideValue, instance):
        '''
		Switches the carousel depending on which slide is n view.
		The method takes two additional attributes:
		-	The target slide for the button press.
		-	The instance of the item (Kivy)
		'''

        try:
            if self.carousel.index != slideValue:
                self.carousel.load_slide(self.carousel.slides[slideValue])
        except:
            pass

    # Allow application pause/minimise on Android systems
    def on_pause(self):
        '''
		This is required to keep the application in an "Alive state" while 
		minimized on Android systmes.
		'''

        return True

    #File Selected - Gather the path
    def fileSelect(self, kivyObject, selectedDir, position):
        '''
		The object of this method is to gather the file information, 
		once this has been established the file is transfered over the 
		network using twisted. 
		
		The method takes 3 variables by default(Kivy):
		-	The instance information.
		-	The selected directory location.		
		-	The positional informaiton
		'''

        # Process the directory information
        self.direct = selectedDir[0]
        x = self.direct
        x = self.direct.split("/")
        self.direct = str(x[-1])

        # Call Twisted
        self.twistIt(selectedDir[0])

    # Call twisted functionality
    def twistIt(self, fileValue):
        '''
		This method calls the Twisted functionality of the program.
		-	The method takes onf additional value representing the files locaiton.
		'''

        # Define the factory
        self.factory = NukeBoxClientFactory(fileValue)
        # Set up protocol
        self.udp_protocol = NukeBoxClientBroadcastProtocol(self.factory)
        # Listen for the server
        reactor.listenUDP(0, self.udp_protocol)
예제 #26
0
class ChrisWindow(GridLayout):
    #Class variables
    red = 1
    green = 1
    blue = 1
    alpha = 1
    color_vector = [red, green, blue, alpha]

    def __init__(self, **kwargs):
        super().__init__(**kwargs)  #call __init__() of parent
        self.cols = 1  #initial configuration for start page

        self._acquireInputFile()
        self._setupStartPage()

    def getColorVector(self):
        """Returns the class variable color_vector."""
        return self.color_vector

    def _acquireInputFile(self):
        """Sets the input file depending on whether a CLI was given."""
        if len(sys.argv) > 1:
            self.cur_file = sys.argv[1]

            #get full path of input file; may need to be updated
            self.cur_file = os.path.abspath(self.cur_file)
            print(self.cur_file)
        else:
            self.cur_file = "None"

    def _setupStartPage(self):
        """Creates the start page for the application."""
        startup_page_label = Label(text="Metadata Music Editor",
                                   font_size="50sp")
        self.add_widget(startup_page_label)
        start_but = Button(text="Start Editing File",
                           background_color=self.color_vector,
                           size_hint_x=0.5,
                           size_hint_y=0.1)
        start_but.bind(on_press=self._transferToEditor)
        self.add_widget(start_but)

    def _transferToEditor(self, instance):
        """Clears startup page to populate root with editor widgets"""
        self.clear_widgets()
        self.cols = 2  #update number of columns for new window
        self._setupEditorWindow()

    def _setupEditorWindow(self):
        """Creates the widget items, their attributes, and their callbacks. """
        self.input_widget_store = []

        self.cur_file_label = Label(
            text="File being edited: {}".format(self.cur_file))
        self.add_widget(self.cur_file_label)

        #Apply changes button
        self.apply_but = Button(text="Apply Changes?",
                                background_color=self.color_vector)
        self.apply_but.bind(on_press=self._applyChangesCallback)
        self.add_widget(self.apply_but)

        #Name of song
        self.name_label = Label(text="Track Name:",
                                color=self.color_vector,
                                font_size=20)
        self.add_widget(self.name_label)

        self.name_input = TextInput(multiline=False)
        self.add_widget(self.name_input)

        self.input_widget_store.append(self.name_input)

        #Artist of song
        self.artist_label = Label(text="Artist Name:",
                                  color=self.color_vector,
                                  font_size=20)
        self.add_widget(self.artist_label)

        self.artist_input = TextInput(multiline=False)
        self.add_widget(self.artist_input)

        self.input_widget_store.append(self.artist_input)

        #Track Number of song
        self.track_num_label = Label(text="Track Number:",
                                     color=self.color_vector,
                                     font_size=20)
        self.add_widget(self.track_num_label)

        self._createTrackNumberWidget(
        )  #Setup a grid within the parent grid layout

        #Album name of song
        self.album_label = Label(text="Album Name:",
                                 color=self.color_vector,
                                 font_size=20)
        self.add_widget(self.album_label)

        self.album_input = TextInput(multiline=False)
        self.add_widget(self.album_input)

        self.input_widget_store.append(self.album_input)

        # Date of song
        self.date_label = Label(text="Release Date (mon/day/yr):",
                                color=self.color_vector,
                                font_size=20)
        self.add_widget(self.date_label)

        self.date_input = TextInput(multiline=False)
        self.add_widget(self.date_input)

        self.input_widget_store.append(self.date_input)

        # Genre of song
        self.genre_label = Label(text="Genre:",
                                 color=self.color_vector,
                                 font_size=20)
        self.add_widget(self.genre_label)

        self.genre_input = TextInput(multiline=False)
        self.add_widget(self.genre_input)

        self.input_widget_store.append(self.genre_input)

        #Get pic button
        self.select_pic_but = Button(text="Find cover art.",
                                     background_color=self.color_vector)
        self.select_pic_but.bind(on_press=self._acquireCoverArt)
        self.add_widget(self.select_pic_but)

        self.pic_selection = "No picture selected."  #variable for storing file path of image that is selected

        #Convert to Flac option
        self.conversion_spinner = Spinner(text="No conversion.",
                                          values=("No conversion",
                                                  "Convert to Flac."))
        self.add_widget(self.conversion_spinner)

    def _createTrackNumberWidget(self):
        """Creates a combined widget to be embedded into the editor view."""
        self.embedded_box = GridLayout(cols=2)
        track_color = [0, 0, 1, 1]
        self.track_num_widget = Slider(min=1,
                                       max=15,
                                       value=1,
                                       value_track=True,
                                       step=1,
                                       value_track_color=track_color)
        self.track_num_inner_label = Label(text=str(
            self.track_num_widget.value),
                                           color=track_color,
                                           size_hint_x=0.3)

        def updateInnerLabel(instance, value):
            """Callback for updating inner label to display slider value."""
            self.track_num_inner_label.text = str(value)

        self.track_num_widget.bind(value=updateInnerLabel)

        self.embedded_box.add_widget(self.track_num_widget)
        self.embedded_box.add_widget(self.track_num_inner_label)

        self.add_widget(self.embedded_box)

    def _acquireCoverArt(self, instance):
        """Creates a window for the user to select a cover art image from the file system."""
        self.pic_selection = "No picture selected."

        user_path = expanduser('~') + sep + 'Pictures'

        self.file_chooser = FileChooserListView(
            path=user_path, filters=["*.jpg", "*.jpeg", "*.png"])
        self.file_chooser.bind(on_submit=self._retrieveFileSelection)

        self.close_button = Button(text="Close", size_hint_y=None, height=30)
        self.close_button.bind(on_press=self._dismissFileSelectionWindow)

        self.file_chooser_grid = GridLayout(rows=2)
        self.file_chooser_grid.add_widget(self.close_button)
        self.file_chooser_grid.add_widget(self.file_chooser)

        self.file_chooser_window = Popup(title="Image Selector",
                                         content=self.file_chooser_grid)
        self.file_chooser_window.open()

    def _retrieveFileSelection(self, instance, selection, touch):
        """Prints file when it is sucessfully retrieved."""
        print("Retrieved: {}".format(selection[0]))
        self.pic_selection = selection[0]
        self.file_chooser_window.dismiss()

    def _dismissFileSelectionWindow(self, instance):
        """Handles the dismiss event of the popup window for selecting an image file."""
        if self.pic_selection == "No picture selected.":
            print("Failure to retrieve file image.")
        else:
            print("Retrieved an image file successfully.")
        self.file_chooser_window.dismiss()

    def _applyChangesCallback(self, instance):
        """Callback() for button widget. """
        print("Button was pressed for the `{}` widget.\n".format(
            instance.text))

        self.needToConvert = False  #controls whether input file must be converted to flac
        self.needToChangeCoverArt = False  #controls whether the cover art image will be changed

        self.tag_pairs = [
        ]  #a list of lists w/ 1st element as TAG to change & 2nd as value
        self.possible_tags = [
            "TITLE", "ARTIST", "ALBUM", "DATE", "GENRE", "TRACKNUMBER"
        ]

        count = 0
        for input_wig in self.input_widget_store:
            pair = []

            if input_wig.text == "":  #checks for empty strings & inapproriate names
                print("Input is invalid -> \'{}\'".format(input_wig.text))
            else:
                pair.append(
                    self.possible_tags[count])  #append corresponding tag
                pair.append(input_wig.text)
                self.tag_pairs.append(pair)

            count = count + 1

        self.tag_pairs.append(["TRACKNUMBER", self.track_num_widget.value])
        print(int(self.track_num_widget.value))

        self.tag_pairs.reverse(
        )  #changes TITLE tag last because it causes file name to change

        print(self.conversion_spinner.text)

        if self.conversion_spinner.text != "No conversion." and ".flac" not in self.cur_file:
            self.needToConvert = True

        print(self.pic_selection)
        if self.pic_selection != "No picture selected.":
            self.needToChangeCoverArt = True

        self.clear_widgets()

        #maybe put a wait screen here: self._showWaitScreen()
        self._applyChanges()
        self._setupFinishScreen()

    def _applyChanges(self):
        """Performs any changes requested via GUI."""

        if self.needToConvert:
            self.cur_file = mcf.convertFileToFlac(
                self.cur_file)  #convert to flac & update file name

        if self.needToChangeCoverArt:
            mdt.setCoverArt(self.pic_selection, self.cur_file)

        if self.cur_file == 'None' or ".flac" not in self.cur_file:
            print("Invaid input file.")
        else:
            for i in range(len(self.tag_pairs)):
                mdt.changeTagValue(self.tag_pairs[i][0], self.tag_pairs[i][1],
                                   self.cur_file)

    def _setupFinishScreen(self):
        """Shows final screen if changes worked."""
        self.add_widget(Label(text="Done. Please, exit the application."))
        return
예제 #27
0
class ScreenManager(FloatLayout):
    log = None
    logpath = ''
    
    def __init__(self, **kwargs):
        super(ScreenManager, self).__init__(**kwargs)

        EventLoop.window.bind(on_keyboard=self.goback)
        
        self.startmenu = StartMenu()
        self.startmenu.filebtn.bind(on_press=self.selectfile)
        self.add_widget(self.startmenu)
        
        self.filemenu = FileChooserListView()
        self.filemenu.bind(on_submit=self.openfile)
        
        self.mode_menu = None
        
    def selectfile(obj, value):
        # wait for old input to clear
        Clock.schedule_once(partial(obj.switchscreen, obj.filemenu), 0.15)

    def openfile(obj, value, selected, event):
        progbar = ProgressBar()
        
        obj.logpath = selected
        obj.switchscreen(progbar)
        obj.tlog = mp.TelemetryLog(selected[0], progbar, obj.postopen, obj.posterror)

    #callback for succesfully opening a log
    def postopen(self, dt):
        
        if self.tlog is None:
            return
        else:
            self.log = self.tlog.packets
            
        self.mode_menu = ModeMenu()
        self.mode_menu.readbtn.bind(on_press=self.readlog)
        self.mode_menu.graphbtn.bind(on_press=self.graphlog)
        self.mode_menu.exportbtn.bind(on_press=self.exportmenu)
        
        self.switchscreen(self.mode_menu)

    #callback for encountering an error
    #while opening a log
    def posterror(self, message, dt):
        print(message)
        self.switchscreen(self.startmenu)
        errorpopup = Popup(title='Error',
                      content=Label(text=message),
                           size_hint=(None, None), size=(600,200))
        errorpopup.open()
        
    def readlog(obj, value):
        rl = Reader(obj.log)
        obj.switchscreen(rl)
        
    def graphlog(obj, value):
        graph = TelemetryGraphScreen(obj, obj.log)

    def exportmenu(obj, value):
        obj.switchscreen(ExportMenu(obj.log, obj.logpath))
        
    def switchscreen(self, widget, *args):
        self.clear_widgets()
        self.add_widget(widget)
    
    def goback(self, window, key, *args):
        if key == 27:
            exit_on_back = StartMenu
            startmenu_on_back = (FileChooserListView, ModeMenu)
  
            if isinstance(self.children[0], exit_on_back):
                return False

            if isinstance(self.children[0], startmenu_on_back):
                self.switchscreen(self.startmenu)
            else:
                self.switchscreen(self.mode_menu)
            
            return True
예제 #28
0
class Admin(Screen):
    container = ObjectProperty(None)
    clothing_dict = {}

    def __init__(self, **kwargs):
        super(Admin, self).__init__(**kwargs)
        Clock.schedule_once(self.setup_scrollview, 1)

    def setup_scrollview(self, dt):
        self.container.bind(minimum_height=self.container.setter('height'))
        self.load_images()

    def edit_item(self, instance):
        # Convert digital data to binary format (Blob)
        def convertToBinaryData(filename):
            with open(filename, 'rb') as file:
                binaryData = file.read()
            return binaryData

        # Update blob image file
        def update_BLOB(photo):
            try:
                connection = mysql.connector.connect(host='localhost',
                                                     database='tashira',
                                                     user='******',
                                                     password='')

                cursor = connection.cursor()

                itemPicture = convertToBinaryData(photo)
                itemName = instance.id[5:-4]

                if "." in isolate_filename(edit_filechooser.selection[0][:-4]):
                    newName = isolate_filename(
                        edit_filechooser.selection[0][:-5])
                else:
                    newName = isolate_filename(
                        edit_filechooser.selection[0][:-4])

                query = "UPDATE clothing " \
                        "SET image = %s " \
                        "WHERE name  = %s"
                query2 = "UPDATE clothing SET name = %s WHERE name = %s"

                args = (itemPicture, itemName)
                args2 = (newName, itemName)

                # Attempt to execute SQL
                try:
                    cursor.execute(query, args)
                    cursor.execute(query2, args2)
                    os.remove("Clothing\\" + str(instance.id))
                # Duplicate found
                except:
                    duplicate_box = BoxLayout()
                    duplicate_cancel = Button(text='Close')

                    duplicate_box.add_widget(duplicate_cancel)

                    duplicate_popup = Popup(content=duplicate_box,
                                            title="This item already exists",
                                            auto_dismiss=True,
                                            size_hint=(None, None),
                                            size=(400, 100))

                    duplicate_cancel.bind(on_release=duplicate_popup.dismiss)
                    duplicate_popup.open()

                connection.commit()

            except Error as error:
                print(error)

            finally:
                cursor.close()
                connection.close()
                self.refresh_page()

        # Isolate the filename from its path
        def isolate_filename(path):
            head, tail = ntpath.split(path)
            return tail or ntpath.basename(head)

        # Update Database and list of items to include the updated entry
        def update_item_list(instance):

            # Nothing selected Error
            if not edit_filechooser.selection:
                none_box = BoxLayout()
                none_cancel = Button(text='Close')
                none_box.add_widget(none_cancel)

                none_popup = Popup(content=none_box,
                                   title="Error: Nothing selected",
                                   auto_dismiss=True,
                                   size_hint=(None, None),
                                   size=(400, 100))

                # Bind Cancel button to dismiss popup
                none_cancel.bind(on_release=none_popup.dismiss)
                none_popup.open()

            # Image was selected
            elif isolate_filename(str(edit_filechooser.selection[0]
                                      [-4:])) in imagefile_extensions:
                # Check if final 4 characters contain period - to separate jpeg from jpg
                if "." in isolate_filename(
                        str(edit_filechooser.selection[0][:-4])):
                    update_BLOB(str(edit_filechooser.selection[0]))
                else:
                    update_BLOB(str(edit_filechooser.selection[0]))

                read_blob("Clothing\\")

                self.refresh_page()
                edit_popup.dismiss()

            # Non-Image was selected
            else:
                error_box = BoxLayout()
                popup_cancel = Button(text='Close')
                error_box.add_widget(popup_cancel)

                error_popup = Popup(content=error_box,
                                    title="Error: File is not an Image",
                                    auto_dismiss=True,
                                    size_hint=(None, None),
                                    size=(400, 100))

                # Bind Cancel button to dismiss popup
                popup_cancel.bind(on_release=error_popup.dismiss)
                error_popup.open()

        # create content and add to the popup
        edit_box = GridLayout(rows=3)

        edit_filechooser = FileChooserListView(path=r'C:')
        edit_filechooser.bind(
            on_selection=lambda x: self.selected(edit_filechooser.selection))
        edit_box.add_widget(edit_filechooser)

        # Open / Cancel buttons
        edit_open_btn = Button(text='Open',
                               size_hint=(None, None),
                               height=40,
                               width=self.width - 25)
        edit_open_btn.bind(on_release=update_item_list)

        edit_cancel_btn = Button(text="Cancel",
                                 size_hint=(None, None),
                                 height=40,
                                 width=self.width - 25)

        edit_box.add_widget(edit_open_btn)
        edit_box.add_widget(edit_cancel_btn)

        edit_popup = Popup(
            content=edit_box,
            title="Choose an image",
            auto_dismiss=True,
        )

        edit_cancel_btn.bind(on_release=edit_popup.dismiss)

        # Open the popup
        edit_popup.open()

    def add_item(self, instance):

        # Convert digital data to binary format (Blob)
        def convertToBinaryData(filename):
            with open(filename, 'rb') as file:
                binaryData = file.read()
            return binaryData

        def insert_BLOB(item_id, name, photo):
            try:
                connection = mysql.connector.connect(host='localhost',
                                                     database='tashira',
                                                     user='******',
                                                     password='')

                cursor = connection.cursor()
                query = " INSERT INTO clothing (id, name, image) VALUES (%s,%s,%s)"

                itemPicture = convertToBinaryData(photo)

                # Convert data into tuple format
                insert_blob_tuple = (item_id, name, itemPicture)
                cursor.execute(query, insert_blob_tuple)
                connection.commit()

            except Error as error:

                print(error)

            finally:
                cursor.close()
                connection.close()

        # Isolate the filename from its path
        def isolate_filename(path):
            head, tail = ntpath.split(path)
            return tail or ntpath.basename(head)

        # Insert into Database and update the list of items to include the new entry
        def update_item_list(instance):

            # Nothing selected Error
            if not self.add_filechooser.selection:
                none_box = BoxLayout()
                none_cancel = Button(text='Close')
                none_box.add_widget(none_cancel)

                none_popup = Popup(content=none_box,
                                   title="Error: Nothing selected",
                                   auto_dismiss=True,
                                   size_hint=(None, None),
                                   size=(400, 100))

                # Bind Cancel button to dismiss popup
                none_cancel.bind(on_release=none_popup.dismiss)
                none_popup.open()

            # Image was selected
            elif isolate_filename(str(self.add_filechooser.selection[0]
                                      [-4:])) in imagefile_extensions:

                query_name = isolate_filename(
                    str(self.add_filechooser.selection[0][:-4]))
                if 'item_' in query_name:
                    query_name = query_name[5:]

                query = 'SELECT * FROM clothing WHERE name = "' + query_name + '"'
                try:
                    connection = mysql.connector.connect(host='localhost',
                                                         database='tashira',
                                                         user='******',
                                                         password='')
                    cursor = connection.cursor(buffered=True)
                    cursor.execute(query)
                    result = cursor.rowcount
                except Error as e:
                    print(e)
                finally:
                    cursor.close()
                    connection.close()
                    self.refresh_page()

                if result == 0:
                    # Check if final 4 characters contain period - to separate jpeg from jpg
                    if "." in isolate_filename(
                            str(self.add_filechooser.selection[0][:-4])):
                        insert_BLOB(
                            'NULL',
                            isolate_filename(
                                str(self.add_filechooser.selection[0][:-5])),
                            str(self.add_filechooser.selection[0]))
                    else:
                        insert_BLOB(
                            'NULL',
                            isolate_filename(
                                str(self.add_filechooser.selection[0][:-4])),
                            str(self.add_filechooser.selection[0]))
                else:
                    add_duplicate_box = BoxLayout()
                    add_duplicate_cancel = Button(text='Close')

                    add_duplicate_box.add_widget(add_duplicate_cancel)

                    add_duplicate_popup = Popup(
                        content=add_duplicate_box,
                        title="This item already exists",
                        auto_dismiss=True,
                        size_hint=(None, None),
                        size=(400, 100))

                    # Bind Cancel button to dismiss popup
                    add_duplicate_cancel.bind(
                        on_release=add_duplicate_popup.dismiss)
                    add_duplicate_popup.open()

                read_blob("Clothing\\")

                self.refresh_page()
                popup.dismiss()

            # Non-Image was selected
            else:
                error_box = BoxLayout()
                popup_cancel = Button(text='Close')
                error_box.add_widget(popup_cancel)

                error_popup = Popup(content=error_box,
                                    title="Error: File is not an Image",
                                    auto_dismiss=True,
                                    size_hint=(None, None),
                                    size=(400, 100))

                # Bind Cancel button to dismiss popup
                popup_cancel.bind(on_release=error_popup.dismiss)
                error_popup.open()

        # create content and add to the popup
        popup_box = GridLayout(rows=3)

        self.add_filechooser = FileChooserListView(path=r'C:')
        self.add_filechooser.bind(on_selection=lambda x: self.selected(
            self.add_filechooser.selection))
        popup_box.add_widget(self.add_filechooser)

        # Open / Cancel buttons
        open_btn = Button(text='Open',
                          size_hint=(None, None),
                          height=40,
                          width=self.width - 25)
        open_btn.bind(on_release=update_item_list)

        cancel_btn = Button(text="Cancel",
                            size_hint=(None, None),
                            height=40,
                            width=self.width - 25)

        popup_box.add_widget(open_btn)
        popup_box.add_widget(cancel_btn)

        popup = Popup(
            content=popup_box,
            title="Choose an image",
            auto_dismiss=True,
        )

        cancel_btn.bind(on_release=popup.dismiss)

        # Open the popup
        popup.open()

    # Set ID/name to delete
    def delete_setup(self, instance):

        # Popup window for delete button confirmation
        def delete_popup(instance):
            # create content and add to the popup
            popup_box = BoxLayout()
            popup_confirm = Button(text='Confirm')
            popup_cancel = Button(text='Cancel')

            popup_box.add_widget(popup_confirm)
            popup_box.add_widget(popup_cancel)

            popup = Popup(content=popup_box,
                          title="Are you sure you want to delete this item?",
                          auto_dismiss=True,
                          size_hint=(None, None),
                          size=(400, 100))

            # Bind Cancel button to dismiss popup
            popup_cancel.bind(on_release=popup.dismiss)

            # This is to bind the Confirm button to 2 functions - dismiss the popup, then run delete_items()
            def pop_delete(instance):
                popup.dismiss()
                delete_items(instance)

            popup_confirm.bind(on_release=pop_delete)

            popup.open()

        # Delete items locally and in Database
        def delete_items(instance):
            if os.path.exists('Clothing/' + clothing_name_full):
                os.remove('Clothing/' + clothing_name_full)

                query = "DELETE FROM clothing WHERE name = '" + str(
                    clothing_name) + "'"

                try:
                    connection = mysql.connector.connect(host='localhost',
                                                         database='tashira',
                                                         user='******',
                                                         password='')
                    cursor = connection.cursor()
                    cursor.execute(query)
                    connection.commit()

                    print(cursor.rowcount, "record(s) deleted from database")
                except Error as e:
                    print(e)
                finally:
                    cursor.close()
                    connection.close()
                    self.refresh_page()
            else:
                print("The file does not exist")

        # Clothing id is used as index in the clothing folder
        clothing_id = instance.id

        # check if final 4 characters in string contains a period, to separate jpg from jpeg
        if "." in os.listdir('Clothing/')[int(clothing_id) - 1][-4:]:
            clothing_name = os.listdir('Clothing/')[int(clothing_id) - 1][5:-4]
        else:
            clothing_name = os.listdir('Clothing/')[int(clothing_id) - 1][5:-5]
        # Full non-sliced file name
        clothing_name_full = os.listdir('Clothing/')[int(clothing_id) - 1]
        # Run delete_popup()
        delete_popup(instance)

    # Create a dictionary with the images / buttons to display on the page, then add them to the page
    def load_images(self):
        dir_name = 'Clothing/'
        file_count = sum([len(files) for r, d, files in os.walk(dir_name)])

        self.add_item_button.bind(on_release=self.add_item)

        # For every file in the Clothing directory
        for x in range(file_count):

            # Add an image from Clothing/ and its Edit/Delete buttons to self.clothing_dict at index[x] as a tuple
            self.clothing_dict[x] = (ImageButton(source="Clothing\\" +
                                                 os.listdir(dir_name)[x],
                                                 size_hint_y=None,
                                                 height=200,
                                                 id=str(x + 1)),
                                     Button(text='Edit',
                                            id=str(os.listdir(dir_name)[x]),
                                            size=(80, 60),
                                            size_hint=(None, None)),
                                     Button(text='Delete',
                                            id=str(x + 1),
                                            size=(80, 60),
                                            size_hint=(None, None)))

        # Bind the buttons from dictionary
        for x in range(len(self.clothing_dict)):
            self.clothing_dict[x][1].bind(on_release=self.edit_item)
            self.clothing_dict[x][2].bind(on_release=self.delete_setup)

        # Add stuff from the dictionary into the page container
        for x in range(len(self.clothing_dict)):
            for y in range(len(self.clothing_dict[x])):
                self.container.add_widget(self.clothing_dict[x][y])

    def refresh_page(self):
        self.clothing_dict.clear(
        )  # clear dictionary to rebuild it in load_images() without deleted item
        self.container.clear_widgets()  # clear all widgets from container
        self.load_images()  # re-add widgets without deleted item
예제 #29
0
    def edit_item(self, instance):
        # Convert digital data to binary format (Blob)
        def convertToBinaryData(filename):
            with open(filename, 'rb') as file:
                binaryData = file.read()
            return binaryData

        # Update blob image file
        def update_BLOB(photo):
            try:
                connection = mysql.connector.connect(host='localhost',
                                                     database='tashira',
                                                     user='******',
                                                     password='')

                cursor = connection.cursor()

                itemPicture = convertToBinaryData(photo)
                itemName = instance.id[5:-4]

                if "." in isolate_filename(edit_filechooser.selection[0][:-4]):
                    newName = isolate_filename(
                        edit_filechooser.selection[0][:-5])
                else:
                    newName = isolate_filename(
                        edit_filechooser.selection[0][:-4])

                query = "UPDATE clothing " \
                        "SET image = %s " \
                        "WHERE name  = %s"
                query2 = "UPDATE clothing SET name = %s WHERE name = %s"

                args = (itemPicture, itemName)
                args2 = (newName, itemName)

                # Attempt to execute SQL
                try:
                    cursor.execute(query, args)
                    cursor.execute(query2, args2)
                    os.remove("Clothing\\" + str(instance.id))
                # Duplicate found
                except:
                    duplicate_box = BoxLayout()
                    duplicate_cancel = Button(text='Close')

                    duplicate_box.add_widget(duplicate_cancel)

                    duplicate_popup = Popup(content=duplicate_box,
                                            title="This item already exists",
                                            auto_dismiss=True,
                                            size_hint=(None, None),
                                            size=(400, 100))

                    duplicate_cancel.bind(on_release=duplicate_popup.dismiss)
                    duplicate_popup.open()

                connection.commit()

            except Error as error:
                print(error)

            finally:
                cursor.close()
                connection.close()
                self.refresh_page()

        # Isolate the filename from its path
        def isolate_filename(path):
            head, tail = ntpath.split(path)
            return tail or ntpath.basename(head)

        # Update Database and list of items to include the updated entry
        def update_item_list(instance):

            # Nothing selected Error
            if not edit_filechooser.selection:
                none_box = BoxLayout()
                none_cancel = Button(text='Close')
                none_box.add_widget(none_cancel)

                none_popup = Popup(content=none_box,
                                   title="Error: Nothing selected",
                                   auto_dismiss=True,
                                   size_hint=(None, None),
                                   size=(400, 100))

                # Bind Cancel button to dismiss popup
                none_cancel.bind(on_release=none_popup.dismiss)
                none_popup.open()

            # Image was selected
            elif isolate_filename(str(edit_filechooser.selection[0]
                                      [-4:])) in imagefile_extensions:
                # Check if final 4 characters contain period - to separate jpeg from jpg
                if "." in isolate_filename(
                        str(edit_filechooser.selection[0][:-4])):
                    update_BLOB(str(edit_filechooser.selection[0]))
                else:
                    update_BLOB(str(edit_filechooser.selection[0]))

                read_blob("Clothing\\")

                self.refresh_page()
                edit_popup.dismiss()

            # Non-Image was selected
            else:
                error_box = BoxLayout()
                popup_cancel = Button(text='Close')
                error_box.add_widget(popup_cancel)

                error_popup = Popup(content=error_box,
                                    title="Error: File is not an Image",
                                    auto_dismiss=True,
                                    size_hint=(None, None),
                                    size=(400, 100))

                # Bind Cancel button to dismiss popup
                popup_cancel.bind(on_release=error_popup.dismiss)
                error_popup.open()

        # create content and add to the popup
        edit_box = GridLayout(rows=3)

        edit_filechooser = FileChooserListView(path=r'C:')
        edit_filechooser.bind(
            on_selection=lambda x: self.selected(edit_filechooser.selection))
        edit_box.add_widget(edit_filechooser)

        # Open / Cancel buttons
        edit_open_btn = Button(text='Open',
                               size_hint=(None, None),
                               height=40,
                               width=self.width - 25)
        edit_open_btn.bind(on_release=update_item_list)

        edit_cancel_btn = Button(text="Cancel",
                                 size_hint=(None, None),
                                 height=40,
                                 width=self.width - 25)

        edit_box.add_widget(edit_open_btn)
        edit_box.add_widget(edit_cancel_btn)

        edit_popup = Popup(
            content=edit_box,
            title="Choose an image",
            auto_dismiss=True,
        )

        edit_cancel_btn.bind(on_release=edit_popup.dismiss)

        # Open the popup
        edit_popup.open()
예제 #30
0
class ScreenManager(FloatLayout):
    log = None
    logpath = ''

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

        EventLoop.window.bind(on_keyboard=self.goback)

        self.startmenu = StartMenu()
        self.startmenu.filebtn.bind(on_press=self.selectfile)
        self.add_widget(self.startmenu)

        self.filemenu = FileChooserListView()
        self.filemenu.bind(on_submit=self.openfile)

        self.mode_menu = None

    def selectfile(obj, value):
        # wait for old input to clear
        Clock.schedule_once(partial(obj.switchscreen, obj.filemenu), 0.15)

    def openfile(obj, value, selected, event):
        progbar = ProgressBar()

        obj.logpath = selected
        obj.switchscreen(progbar)
        obj.tlog = mp.TelemetryLog(selected[0], progbar, obj.postopen,
                                   obj.posterror)

    #callback for succesfully opening a log
    def postopen(self, dt):

        if self.tlog is None:
            return
        else:
            self.log = self.tlog.packets

        self.mode_menu = ModeMenu()
        self.mode_menu.readbtn.bind(on_press=self.readlog)
        self.mode_menu.graphbtn.bind(on_press=self.graphlog)
        self.mode_menu.exportbtn.bind(on_press=self.exportmenu)

        self.switchscreen(self.mode_menu)

    #callback for encountering an error
    #while opening a log
    def posterror(self, message, dt):
        print(message)
        self.switchscreen(self.startmenu)
        errorpopup = Popup(title='Error',
                           content=Label(text=message),
                           size_hint=(None, None),
                           size=(600, 200))
        errorpopup.open()

    def readlog(obj, value):
        rl = Reader(obj.log)
        obj.switchscreen(rl)

    def graphlog(obj, value):
        graph = TelemetryGraphScreen(obj, obj.log)

    def exportmenu(obj, value):
        obj.switchscreen(ExportMenu(obj.log, obj.logpath))

    def switchscreen(self, widget, *args):
        self.clear_widgets()
        self.add_widget(widget)

    def goback(self, window, key, *args):
        if key == 27:
            exit_on_back = StartMenu
            startmenu_on_back = (FileChooserListView, ModeMenu)

            if isinstance(self.children[0], exit_on_back):
                return False

            if isinstance(self.children[0], startmenu_on_back):
                self.switchscreen(self.startmenu)
            else:
                self.switchscreen(self.mode_menu)

            return True
예제 #31
0
class MemeAppMainView(GridLayout):
    def __init__(self, main_app, **kwargs):
        super(MemeAppMainView, self).__init__(**kwargs)
        self.main_app = main_app
        self.cols = 2

        self.text_grid = GridLayout(rows=5, size_hint_x=None, width=400)

        self.load_button = Button(text='Select Image', size_hint=(1.0, 0.25))
        self.load_button.bind(on_press=self.select_image)

        self.save_button = Button(text='Save', size_hint=(1.0, 0.25))
        self.save_button.bind(on_press=self.save_image)

        self.text_grid.add_widget(MemeTextBox(self.on_top_changed))
        self.text_grid.add_widget(MemeTextBox(self.on_mid_changed))
        self.text_grid.add_widget(MemeTextBox(self.on_bot_changed))
        self.text_grid.add_widget(self.load_button)
        self.text_grid.add_widget(self.save_button)
        self.add_widget(self.text_grid)

        # Sadly can't load from a buffer and need to create files with current strategy. :(
        self.main_app.meme.render_no_text('preview.gif')
        self.main_app.meme.render_text_image('text.png')
        self.image_view = Image(source='preview.gif',
                                anim_delay=0.05,
                                pos_hint={
                                    'x': 0,
                                    'y': 0
                                },
                                allow_stretch=True,
                                keep_ratio=True)
        self.image_text = Image(source='text.png',
                                pos_hint={
                                    'x': 0,
                                    'y': 0
                                },
                                allow_stretch=True,
                                keep_ratio=True)
        self.image_float = FloatLayout()
        self.image_float.add_widget(self.image_view)
        self.image_float.add_widget(self.image_text)
        self.add_widget(self.image_float)

        self.file_select_view = Popup(title='Select Image')
        self.file_chooser = FileChooserListView(rootpath='./')
        self.file_chooser.bind(on_submit=self.on_image_selected)
        self.file_select_view.add_widget(self.file_chooser)

    def on_top_changed(self, value, align):
        self.main_app.set_top(value)
        self.main_app.meme.set_top_align(align)
        self.main_app.meme.render_text_image('text.png')
        self.image_text.reload()

    def on_mid_changed(self, value, align):
        self.main_app.set_mid(value)
        self.main_app.meme.set_mid_align(align)
        self.main_app.meme.render_text_image('text.png')
        self.image_text.reload()

    def on_bot_changed(self, value, align):
        self.main_app.set_bot(value)
        self.main_app.meme.set_bot_align(align)
        self.main_app.meme.render_text_image('text.png')
        self.image_text.reload()

    def select_image(self, instance):
        self.file_select_view.open()

    def on_image_selected(self, instance, selection, touch):
        self.file_select_view.dismiss()
        self.main_app.meme.set_input(selection[0])
        self.main_app.meme.render_no_text('preview.gif')
        self.main_app.meme.render_text_image('text.png')
        self.image_text.reload()
        self.image_view.reload()

    def save_image(self, instance):
        self.main_app.meme.render('meme.gif')
예제 #32
0
class Renderer(Widget):
    texture = ObjectProperty(None, allownone=True)

    def load(self, *l):
        self.button.disabled = True

        if os.path.isdir(meshdir):
            rep = meshdir
            self.fl = FileChooserListView(path=rep,
                                          rootpath=rep,
                                          filters=["*.mesh.ascii"],
                                          dirselect=False,
                                          size=(400, 400),
                                          center_x=250,
                                          center_y=250)
        else:
            rep = os.getcwd()
            self.fl = FileChooserListView(path=rep,
                                          filters=["*.mesh.ascii"],
                                          dirselect=False,
                                          size=(400, 400),
                                          center_x=250,
                                          center_y=250)
        '''if platform == 'android':
            rep = "."
        else:
            rep = "../../Mesh"'''

        self.fl.bind(selection=self.on_selected)
        super(Renderer, self).add_widget(self.fl)

    def on_selected(self, filechooser, selection):
        self.button.disabled = False

        print 'load', selection
        super(Renderer, self).remove_widget(self.fl)

        scale = 3
        self.fbo.remove_group('truc')

        self.scene = MeshAsciiLoader(selection[0], scale)

        with self.fbo:
            #ClearBuffers(clear_depth=True)

            self.cb = Callback(self.setup_gl_context)
            PushMatrix()
            self.setup_scene()
            PopMatrix()
            self.cb = Callback(self.reset_gl_context)

    def change_shader(self, *l):
        print 'change_shader'
        if self.shader == 0:
            self.fbo.shader.source = resource_find('simple.glsl')
            self.shader = 1
        else:
            #self.fbo.shader.source = resource_find('flat.glsl')
            self.fbo.shader.source = resource_find('normalmap.glsl')
            self.shader = 0

    def __init__(self, **kwargs):
        self.model = 0
        self.shader = 0
        self.canvas = Canvas()
        #self.scene = ObjFileLoader(resource_find("testnurbs.obj"))

        Logger.debug('******************************************************')
        scale = 3
        #dir = "Duke Nukem Forever_Dr_Valencia" # error index out of range
        #dir = "Duke Nukem Forever_Kitty Pussoix"
        dir = "Duke_Nukem_by_Ventrue"
        #dir = "DOA5U_Rachel_Nurse/Model" #pb uv

        if not os.path.isdir(meshdir):
            self.scene = MeshAsciiLoader(
                resource_find(dir + "/Generic_Item.mesh.ascii"), scale)
        else:
            self.scene = MeshAsciiLoader(
                resource_find(meshdir + dir + "/Generic_Item.mesh.ascii"),
                scale)

        #scale = .03
        #self.texturename = 'Batman_Rabbit_Head_Posed/Batman_V3_Body_D.PNG'
        #self.scene = PSKFileLoader(resource_find("Batman_Rabbit_Head_Posed/Batman_Rabbit_Head_Posed.psk"), scale)
        #self.texturename = 'Gray/Gray_C1.tga'
        #self.scene = PSKFileLoader(resource_find("Gray/Mike_TPP.psk"), scale) #too many indices, good for split test
        #self.texturename = 'CV_Talia/Talia_Body_D.tga'
        #self.texturename = 'CV_Talia/Talia_Legs_D.tga')
        #self.scene = PSKFileLoader(resource_find("CV_Talia/Talia_posed.psk"), scale) #too many indices, good for split test
        Logger.debug('******************************************************')

        with self.canvas:
            self.fbo = Fbo(size=self.size,
                           with_depthbuffer=True,
                           compute_normal_mat=True,
                           clear_color=(0, 0, 0, 0.))
            self.viewport = Rectangle(size=self.size, pos=self.pos)
        #self.fbo.shader.source = resource_find('simple.glsl')
        self.fbo.shader.source = resource_find('normalmap.glsl')

        super(Renderer, self).__init__(**kwargs)

        self.fbo['texture1'] = 1
        self.fbo['toggletexture'] = 1

        with self.fbo:
            #ClearBuffers(clear_depth=True)

            self.cb = Callback(self.setup_gl_context)

            PushMatrix()
            self.setup_scene()
            PopMatrix()
            self.cb = Callback(self.reset_gl_context)

        Clock.schedule_interval(self.update_scene, 1 / 60.)

        self._touches = []

        self.button = Button(text='load')
        self.button.bind(on_release=self.load)
        super(Renderer, self).add_widget(self.button)

        button1 = Button(text='shader', center_x=150)
        button1.bind(on_release=self.change_shader)
        super(Renderer, self).add_widget(button1)

    def on_size(self, instance, value):
        self.fbo.size = value
        self.viewport.texture = self.fbo.texture
        self.viewport.size = value
        self.update_glsl()

    def on_pos(self, instance, value):
        self.viewport.pos = value

    def on_texture(self, instance, value):
        self.viewport.texture = value

    def setup_gl_context(self, *args):
        #clear_buffer
        glEnable(GL_DEPTH_TEST)
        self.fbo.clear_buffer()
        #glDepthMask(GL_FALSE);

    def reset_gl_context(self, *args):
        glDisable(GL_DEPTH_TEST)

    def update_glsl(self, *largs):
        asp = self.width / float(self.height)
        proj = Matrix().view_clip(-asp, asp, -1, 1, 1, 500, 1)
        self.fbo['projection_mat'] = proj
        self.fbo['diffuse_light'] = (1.0, 0.0, 0.0)
        self.fbo['ambient_light'] = (0.1, 0.1, 0.1)
        self.fbo['glLightSource0_position'] = (1.0, 1.0, 1.0, 0.0)
        self.fbo['glLightSource0_spotCutoff'] = 360
        self.fbo['glLightModel_ambient'] = (0.2, 0.2, 0.2, 1.0)
        self.fbo['glLightSource0_diffuse'] = (0.7, 0.7, 0.7, 1.0)
        self.fbo['glLightSource0_specular'] = (.1, .1, .1, 1.0)
        self.fbo['glFrontMaterial_specular'] = (.10, .10, .10, 1.0)
        self.fbo['glFrontMaterial_shininess'] = 0.1

    def setup_scene(self):
        Color(.5, .5, .5, 0)

        PushMatrix()
        Translate(0, -3, -5)
        # This Kivy native Rotation is used just for
        # enabling rotation scene like trackball
        self.rotx = Rotate(0, 1, 0, 0)
        # here just rotate scene for best view
        self.roty = Rotate(180, 0, 1, 0)
        self.scale = Scale(1)

        UpdateNormalMatrix()

        self.draw_elements()

        PopMatrix()

    def draw_elements(self):
        #Draw separately all meshes on the scene
        def _draw_element(m, texture='', texture1=''):
            #bind the texture BEFORE the draw (Mesh)
            if texture1:
                # here, we are binding a custom texture at index 1
                # this will be used as texture1 in shader.
                tex1 = Image(texture1).texture
                tex1.wrap = 'repeat'  #enable of uv support >1 or <0
                BindTexture(texture=tex1, index=1)
            #clear the texture if none
            else:
                BindTexture(source="", index=1)

            mesh = Mesh(
                vertices=m.vertices,
                indices=m.indices,
                fmt=m.vertex_format,
                mode='triangles',
                group='truc',
            )

            if texture:
                try:
                    texture = Image(texture).texture
                    texture.wrap = 'repeat'  #enable of uv support >1 or <0
                    mesh.texture = texture
                except:  #no texture if not found or not supported
                    pass

        def _set_color(*color, **kw):
            id_color = kw.pop('id_color', (0, 0, 0))
            return ChangeState(
                Kd=color,
                Ka=color,
                Ks=(.3, .3, .3),
                Tr=1.,
                Ns=1.,
                intensity=1.,
                id_color=[i / 255. for i in id_color],
            )

        for meshid in range(0, len(self.scene.objects)):
            # Draw each element
            mesh = self.scene.objects[meshid]
            #_set_color(0.7, 0.7, 0., id_color=(255, 255, 0))
            if (mesh.diffuse != ""):
                _draw_element(mesh, mesh.diffuse, mesh.normal)
                #_draw_element(mesh, mesh.diffuse)
                #_draw_element(mesh, mesh.normal)
            else:
                _draw_element(mesh, self.texturename)

    def update_scene(self, *largs):
        pass

    # ============= All stuff after is for trackball implementation ===========

    def define_rotate_angle(self, touch):
        x_angle = (touch.dx / self.width) * 360
        y_angle = -1 * (touch.dy / self.height) * 360
        return x_angle, y_angle

    def on_touch_down(self, touch):
        self._touch = touch
        touch.grab(self)
        self._touches.append(touch)
        return super(Renderer, self).on_touch_down(touch)

    def on_touch_up(self, touch):
        touch.ungrab(self)
        self._touches.remove(touch)
        return super(Renderer, self).on_touch_up(touch)

    def on_touch_move(self, touch):
        self.update_glsl()
        if touch in self._touches and touch.grab_current == self:
            if len(self._touches) == 1:
                # here do just rotation
                ax, ay = self.define_rotate_angle(touch)

                self.roty.angle += ax
                self.rotx.angle += ay

            elif len(self._touches) == 2:  # scaling here
                #use two touches to determine do we need scal
                touch1, touch2 = self._touches
                old_pos1 = (touch1.x - touch1.dx, touch1.y - touch1.dy)
                old_pos2 = (touch2.x - touch2.dx, touch2.y - touch2.dy)

                old_dx = old_pos1[0] - old_pos2[0]
                old_dy = old_pos1[1] - old_pos2[1]

                old_distance = (old_dx * old_dx + old_dy * old_dy)
                #Logger.debug('Old distance: %s' % old_distance)

                new_dx = touch1.x - touch2.x
                new_dy = touch1.y - touch2.y

                new_distance = (new_dx * new_dx + new_dy * new_dy)

                #Logger.debug('New distance: %s' % new_distance)
                SCALE_FACTOR = 0.01

                if new_distance > old_distance:
                    scale = SCALE_FACTOR
                    #Logger.debug('Scale up')
                elif new_distance == old_distance:
                    scale = 0
                else:
                    scale = -1 * SCALE_FACTOR
                    #Logger.debug('Scale down')

                xyz = self.scale.xyz

                if scale:
                    self.scale.xyz = tuple(p + scale for p in xyz)
예제 #33
0
class AssetsEditorPopup():
    def __init__(self, **kwargs):

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

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

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

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

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

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

        self.imageResourceGUIBox.add_widget(self.drivesChooseBox)

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

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

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

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

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

        self.imageResourceGUIBox.add_widget(self.selectedRelativePathLabel)

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

        self.imageResourceGUIBox.add_widget(self.assetNameGUINAme)

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

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

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

        self.imageResourceGUIBox.add_widget(self.assetName)

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

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

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

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

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

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

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

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

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

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

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

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

        assetListHeder.add_widget(headerPreview)

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

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

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

        self.leftBox.add_widget(assetListHeder)

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

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

        self.leftBox.add_widget(self.sceneScroller)

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

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

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

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

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

        self.imageResourceGUIBox.add_widget(self.previewBox)

        self.box.add_widget(self.leftBox)

        self.leftBox.add_widget(self.cancelBtn)

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

    def showAssetGUI(self, item, instance):

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

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

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

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

    def resolveAssetPathFolder(self):

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

            def wtf():
                print('wtf')

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

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

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

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

        print("Assets pack write meta data.")

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

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

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

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

        def catchErr1():
            print("catchErr1")

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

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

    def deleteAsset(self, item, instance):

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

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

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

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

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

    def selfUpdate(self, loadAssetElements):

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

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

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

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

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

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

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

        self.sceneScroller.clear_widgets()

        self.sceneScroller.add_widget(alllocalBox)
예제 #34
0
class SaveAsPopup(Popup):
    def __init__(self, chisel):
        self.chisel = chisel
        self.save_type = None
        self.choices = {
            "background": ".png " + _("(with background)"),
            "transparent": ".png " + _("(transparent)"),
            "project": PROJECT_EXTENSION,
            "all": _("All")
        }

        layout = BoxLayout(orientation="vertical",
                           spacing=dp(34),
                           padding=(dp(20), dp(15)))
        self.file_chooser = FileChooserListView(path=get_saves_path(),
                                                filters=[self._filter_file],
                                                size_hint=(1, 0.75))

        sublayout = BoxLayout(orientation="horizontal",
                              spacing=dp(10),
                              size_hint=(1, 0.1))
        self.text_input = TextInput(text="Untitled",
                                    multiline=False,
                                    font_name=FONT.get(),
                                    font_size=sp(16),
                                    size_hint_x=0.6)
        self.save_type_btn = KivyButton(text=_("Select file type"),
                                        font_name=FONT.get(),
                                        size_hint_x=0.4)
        sublayout.add_widget(self.text_input)
        sublayout.add_widget(self.save_type_btn)

        self.save_btn = Button(_("Please select a file type."),
                               disabled=True,
                               font_size=sp(16),
                               size_hint=(1, 0.15))

        self.file_chooser.bind(path=self._change_title,
                               selection=self._set_text)
        self.text_input.bind(text=self._on_text_input,
                             on_text_validate=self._save_file)
        self.save_type_btn.bind(on_release=self.open_save_type_popup)
        self.save_btn.bind(on_release=self._save_file)

        for widget in (self.file_chooser, sublayout, self.save_btn):
            layout.add_widget(widget)

        super().__init__("", layout, size_hint=(0.7, 0.9))
        self._change_title()

    @staticmethod
    def _filter_file(folder, filename):
        return (filename.endswith(PROJECT_EXTENSION)
                or filename.endswith(".png"))

    def get_maybe_shortened_filename(self):
        string = self.get_resolved_filename()
        if len(string) > 24:
            parts = string.rsplit(".", 1)
            if len(parts) > 1:
                filename, ext = parts
                return filename[:6] + "..." + filename[-5:] + "." + ext
            return parts[0][:6] + "..." + parts[0][-5:]
        return string

    def get_resolved_filename(self):
        string = self.text_input.text
        ext = self._get_file_extension()
        if ext is None:
            return string
        if not string.endswith(ext):
            string += ext
        return string

    def _change_title(self, *args):
        path = self.file_chooser.path
        self.title = _("Save to {path}").format(path=path)

    def _set_text(self, *args):
        selection = self.file_chooser.selection
        if selection:
            self.text_input.text = Path(selection[0]).name

    def _on_text_input(self, *args):
        text = self.text_input.text
        if len(text) > MAX_FILENAME_LENGTH:
            self.text_input.text = text[:MAX_FILENAME_LENGTH]
        if self.save_type:
            current_ext = self._get_file_extension()
            if current_ext == ".png" and self.text_input.text.endswith(
                    PROJECT_EXTENSION):
                self._set_save_type(None, "project")
            elif current_ext == PROJECT_EXTENSION and self.text_input.text.endswith(
                    ".png"):
                self._set_save_type(None, "background")
        else:
            if self.text_input.text.endswith(PROJECT_EXTENSION):
                self._set_save_type(None, "project")
            elif self.text_input.text.endswith(".png"):
                self._set_save_type(None, "background")
        self._change_btn_name()

    def _change_btn_name(self, *args):
        if self.save_type is None:
            return
        self.save_btn.text = _('Save as "{filename}"').format(
            filename=self.get_maybe_shortened_filename())

    def _save_file(self, *args):
        try:
            self._do_saves()
        except OSError:
            open_error_popup(
                _("The file could not be saved due to an error "
                  "raised by the operating system.\nCommon "
                  "issue: Illegal characters in the file name."))
        self.dismiss()

    def open_save_type_popup(self, *args):
        popup = SelectionPopup(_("Select file type"), self.choices)
        popup.bind(choice=self._set_save_type)
        popup.open()

    def _set_save_type(self, instance, choice):
        self.save_type_btn.text = self.choices[choice]
        self.save_btn.disabled = False
        if self.save_type is not None:
            old_ext = self._get_file_extension()
            if old_ext and self.text_input.text.endswith(old_ext):
                self.text_input.text = self.text_input.text[:-len(old_ext)]
        self.save_type = choice
        new_ext = self._get_file_extension()
        if new_ext and not self.text_input.text.endswith(new_ext):
            self.text_input.text += new_ext
        self._change_btn_name()

    def _get_file_extension(self):
        extensions = {
            "background": ".png",
            "transparent": ".png",
            "project": PROJECT_EXTENSION,
            "all": None
        }
        return extensions[self.save_type]

    def _do_saves(self):
        filename = self.get_resolved_filename()
        path = Path(self.file_chooser.path)
        ext = self._get_file_extension()
        if ext is None:
            bg_path = path / (filename + ".png")
            trans_path = path / (filename + "_transparent.png")
            project_path = path / (filename + PROJECT_EXTENSION)
        else:
            bg_path = trans_path = project_path = path / filename

        bg_func = lambda: self.chisel.export_png(bg_path, transparent=False)
        trans_func = lambda: self.chisel.export_png(trans_path,
                                                    transparent=True)
        project_func = lambda: self.chisel.save(project_path)
        all_func = lambda: bg_func() or trans_func() or project_func()
        functions = {
            "background": bg_func,
            "transparent": trans_func,
            "project": project_func,
            "all": all_func
        }
        functions[self.save_type]()

    def on_dismiss(self, *args):
        self.file_chooser.cancel()
예제 #35
0
class ImportPopup(Popup):
    def __init__(self, chisel):
        self.chisel = chisel
        layout = BoxLayout(orientation="vertical",
                           spacing=dp(34),
                           padding=(dp(20), dp(15)))
        self.file_chooser = FileChooserListView(path=get_saves_path(),
                                                filters=[self._filter_file],
                                                size_hint=(1, 0.85))
        self.btn = Button(_("Please select a file."),
                          disabled=True,
                          font_size=sp(16),
                          size_hint=(1, 0.15))

        self.file_chooser.bind(path=self._change_title,
                               selection=self._change_btn_name)
        self.btn.bind(on_release=self._select_file)

        layout.add_widget(self.file_chooser)
        layout.add_widget(self.btn)

        super().__init__("", layout, size_hint=(0.7, 0.9))
        self._change_title()

    @staticmethod
    def _filter_file(folder, filename):
        return filename.endswith(PROJECT_EXTENSION)

    def _change_title(self, *args):
        path = self.file_chooser.path
        self.title = _("Import from {path}").format(path=path)

    def _change_btn_name(self, *args):
        selection = self.file_chooser.selection
        if selection:
            self.btn.text = _('Open "{filename}"').format(
                filename=Path(selection[0]).name)
            self.btn.disabled = False
        else:
            self.btn.text = _("Please select a file.")
            self.btn.disabled = True

    def _select_file(self, *args):
        selection = self.file_chooser.selection
        if selection:
            self.dismiss()
            Window.remove_widget(CURSOR)
            self.loading_popup = open_loading_popup(
                _("Importing the project."))
            Clock.schedule_once(lambda dt: self._load_file(selection[0]), 0.1)

    def _load_file(self, path):
        try:
            self.chisel.load(path)
        except (ValueError, KeyError):
            open_error_popup(_("The file could not be loaded."))
        finally:
            self.loading_popup.dismiss()
            Window.add_widget(CURSOR, "after")

    def on_dismiss(self, *args):
        self.file_chooser.cancel()
예제 #36
0
class AssetsEditorPopupAdd():

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

    def __init__(self, **kwargs):

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

        Window.bind(mouse_pos=self.on_mouse_pos)

        self.operationStatus = True
        self.isFreeRigthBox = True

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

        print("DEBUG", platform)

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

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

        for item in drives:
            print(item)

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


        self.imageResourceGUIBox.add_widget(self.drivesChooseBox)

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

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

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

        self.imageResourceGUIBox.add_widget(self.assetName)

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

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

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

        self.imageResourceGUIBox.add_widget(self.commandBtn)

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

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

        self.imageResourceGUIBox.add_widget(self.previewBox)

        self.box.add_widget(self.leftBox)

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

        self.leftBox.add_widget(self.addImageRes)

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

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

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

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

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

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

        self.popup.open()

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

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

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

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

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

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

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

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

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

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

    def resolveAssetPathFolder(self, typeOfAsset):

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

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

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

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

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

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

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

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

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

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

        self.selectedPathLabel.text = localHandler

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

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

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

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