コード例 #1
0
class NowPlayingScreen(GridLayout):
    def __init__(self, cc, **kwargs):
        super(NowPlayingScreen, self).__init__(**kwargs)
        self.cols = 3
        time.sleep(1)

        self.track_artist = Label(text=cc.media_controller.status.artist)
        self.track_title = Label(text=cc.media_controller.status.title)

        image = next(i for i in cc.media_controller.status.images
                     if i.height > 500)

        self.album_art = AsyncImage(source=image.url)

        # Add the UI elements to the layout:
        self.add_widget(self.track_artist)
        self.add_widget(self.track_title)
        self.add_widget(self.album_art)

    def update_track_title(self, text):
        self.track_title.text = text

    def update_track_artist(self, text):
        self.track_artist.text = text

    def update_album_art(self, media_images):
        self.album_art.source = \
            next(i for i in media_images if i.height > 500).url
        self.album_art.reload()
コード例 #2
0
    def test_reload_asyncimage(self):
        from kivy.resources import resource_find
        from kivy.uix.image import AsyncImage

        temp_dir = mkdtemp()
        event = Event()
        image = AsyncImage()
        image.bind(on_load=lambda *args, **kwargs: event.set())

        fn = resource_find('data/logo/kivy-icon-16.png')
        source = join(temp_dir, 'source.png')
        copyfile(fn, source)
        event.clear()
        image.source = source
        self.wait_for_event_or_timeout(event)
        self.render(image, framecount=2)
        self.assertEqual(image.texture_size, [16, 16])
        remove(source)

        fn = resource_find('data/logo/kivy-icon-32.png')
        copyfile(fn, source)
        event.clear()
        image.reload()
        self.wait_for_event_or_timeout(event)
        self.render(image, framecount=2)
        self.assertEqual(image.texture_size, [32, 32])
        remove(source)
        rmtree(temp_dir)
コード例 #3
0
class MainBox(BoxLayout):
    def __init__(self, *args, **kwargs):
        super(MainBox, self).__init__(**kwargs)
        #~ video = Video(source='http://163.10.10.103', play=True)
        self.video = AsyncImage(
            source=
            'http://*****:*****@163.10.10.103/cgi-bin/viewer/video.jpg',
            nocache=True)
        self.add_widget(self.video)
        Clock.schedule_interval(self.refresh, 1)

    def refresh(self, *evnt):
        print "reload"
        self.video.reload()
コード例 #4
0
    def test_reload_asyncimage(self):
        from kivy.resources import resource_find
        from tempfile import mkdtemp
        from os import remove
        from shutil import copyfile, rmtree

        fn = resource_find('data/logo/kivy-icon-16.png')
        t = mkdtemp()
        source = join(t, 'source.png')
        copyfile(fn, source)
        image = AsyncImage(source=source)
        self.render(image, framecount=2)
        self.assertEqual(image.texture_size, [16, 16])
        remove(source)

        fn = resource_find('data/logo/kivy-icon-32.png')
        copyfile(fn, source)
        image.reload()
        self.render(image, framecount=2)
        self.assertEqual(image.texture_size, [32, 32])
        remove(source)
        rmtree(t)
コード例 #5
0
    def test_reload_asyncimage(self):
        from kivy.resources import resource_find
        from tempfile import mkdtemp
        from os import symlink, unlink
        from shutil import rmtree

        fn = resource_find('data/logo/kivy-icon-16.png')
        t = mkdtemp()
        source = join(t, 'source.png')
        symlink(fn, source)
        image = AsyncImage(source=source)
        self.render(image, framecount=2)
        self.assertEqual(image.texture_size, [16, 16])
        unlink(source)

        fn = resource_find('data/logo/kivy-icon-32.png')
        symlink(fn, source)
        image.reload()
        self.render(image, framecount=2)
        self.assertEqual(image.texture_size, [32, 32])
        unlink(source)
        rmtree(t)
コード例 #6
0
class WidgetContainer(GridLayout, DataHandler):
    def __init__(self, **kwargs):

        # super function can be used to gain access
        # to inherited methods from a parent or sibling
        # class that has been overwritten in a class object.
        super(WidgetContainer, self).__init__(**kwargs)

        self.cols = 3
        self.rows = 3

        self.start_time, self.end_time = self.get_start_parameters()
        self.create_wc(self.start_time, self.end_time)
        self.diff = self.end_time - self.start_time

        self.locked = False

        # declaring the slider and adding some effects to it
        self.start_control = Slider(min=0,
                                    max=100,
                                    value=0,
                                    value_track=True,
                                    value_track_color=[0, 0, 1, 1],
                                    size_hint_y=None,
                                    height=30)
        self.end_control = Slider(min=0,
                                  max=100,
                                  value=100,
                                  value_track=True,
                                  value_track_color=[1, 0, 0, 1],
                                  size_hint_y=None,
                                  height=30)

        # 1st row
        self.add_widget(Label(text='', size_hint_x=None, width=100))
        self.image = AsyncImage(source="./wordcloud.jpg")
        self.add_widget(self.image)
        self.add_widget(Label(text='', size_hint_x=None, width=100))

        # 2nd row
        self.togglebutton = ToggleButton(text='unlocked',
                                         group='slider_lock',
                                         size_hint_x=None,
                                         width=100,
                                         size_hint_y=None,
                                         height=30)
        self.add_widget(self.togglebutton)
        self.add_widget(self.start_control)
        self.start_value = Label(text=datetime.strftime(
            self.start_time, '%Y-%m-%d'),
                                 size_hint_x=None,
                                 width=100,
                                 size_hint_y=None,
                                 height=30)
        self.add_widget(self.start_value)

        # 3rd row
        self.add_widget(
            Label(text='',
                  size_hint_x=None,
                  width=100,
                  size_hint_y=None,
                  height=30))
        self.add_widget(self.end_control)
        self.end_value = Label(text=datetime.strftime(self.end_time,
                                                      '%Y-%m-%d'),
                               size_hint_x=None,
                               width=100,
                               size_hint_y=None,
                               height=30)
        self.add_widget(self.end_value)

        # On the slider objects Attach a callback
        # for the attribute named "value_normalized"
        self.start_control.bind(value_normalized=self.on_value_start)
        self.end_control.bind(value_normalized=self.on_value_end)

        # Attach callback to attribute "state" of togglebutton
        self.togglebutton.bind(state=self.on_pressed)

    # Adding functionality behind the sliders and togglebutton
    # i.e when pressed increase the value
    def on_value_start(self, instance, value):
        print("Changing start point")
        self.start_control.value_normalized = min(
            self.start_control.value_normalized,
            self.end_control.value_normalized)
        value = self.start_control.value_normalized
        self.start_value.text = datetime.strftime(
            self.start_time + self.start_control.value_normalized * self.diff,
            '%Y-%m-%d')
        if self.locked == True:
            print("Changing end point")
            self.end_control.value_normalized = min(
                1, self.start_control.value_normalized + self.locked_diff)
        self.create_wc(
            self.start_time + self.start_control.value_normalized * self.diff,
            self.start_time + self.end_control.value_normalized * self.diff)
        print("Reading image")
        self.image.reload()

    def on_value_end(self, instance, value):
        print("Changing end point")
        self.end_control.value_normalized = max(
            self.end_control.value_normalized,
            self.start_control.value_normalized)
        value = self.end_control.value_normalized
        self.end_value.text = datetime.strftime(
            self.start_time + self.end_control.value_normalized * self.diff,
            '%Y-%m-%d')
        if self.locked == True:
            print("Changing start point")
            self.start_control.value_normalized = max(
                0, self.end_control.value_normalized - self.locked_diff)
        self.create_wc(
            self.start_time + self.start_control.value_normalized * self.diff,
            self.start_time + (self.end_control.value_normalized * self.diff))
        print("Reading image")
        self.image.reload()

    def on_pressed(self, instance, state):
        if state == 'down':
            self.togglebutton.text = "locked"
            self.locked_diff = self.end_control.value_normalized - \
                self.start_control.value_normalized
            self.locked = True
        else:
            self.togglebutton.text = "unlocked"
            self.locked_diff = None
            self.locked = False
コード例 #7
0
class infocard(MDCard, Thread):
    def __init__(self, url, **kwargs):
        self.url = url

        MDCard.__init__(self, **kwargs)
        Thread.__init__(self)
        self.size_hint_y = None
        self.size = (100, 300)
        self.body = GridLayout(cols=1, padding=(2, 5))
        self.desbody = GridLayout(cols=2, size_hint_y=0.5)
        self.downloadbody = GridLayout(cols=2, size_hint_y=0.1)
        self.titlebody = GridLayout(cols=2, size_hint_y=0.1)
        self.title = MDLabel(text='VIDEO TITLE',
                             font_style='Body2',
                             pos_hint={
                                 'center_x': 0.51,
                                 'top': 1.3
                             })
        #self.title.bind(size=self.title.setter('text_size'))
        self.thumb = AsyncImage(source='load.jpg',
                                pos_hint={'center_x': 0},
                                size_hint=(0.2, 1))
        self.descriptionscroll = ScrollView()

        self.description = MDLabel(text='Descriptions',
                                   font_style='Caption',
                                   size_hint_y=None,
                                   pos_hint={
                                       'center_x': 0.5,
                                       'top': 1.15
                                   })
        self.description.bind(texture_size=self.description.setter('size'))
        self.descriptionscroll.add_widget(self.description)
        self.downloadbutton = MDFloatingActionButton(icon='download',
                                                     pos_hint={'right': 1},
                                                     disabled=True)
        self.probar = MDProgressBar(max=100,
                                    pos_hint={
                                        'center_y': 0,
                                        'center_x': 0.4
                                    })
        self.titlebody.add_widget(self.thumb)
        self.titlebody.add_widget(self.title)
        self.desbody.add_widget(self.descriptionscroll)
        self.downloadbody.add_widget(self.probar)
        self.downloadbody.add_widget(self.downloadbutton)
        kvp = '''
#:import MDSpinner kivymd.spinner.MDSpinner
#:import MDCheckbox kivymd.selectioncontrols.MDCheckbox


Screen:

    MDSpinner:
        id: spinner
        size_hint: None, None
        size: dp(46), dp(46)
        pos_hint: {'center_x': 0.5, 'center_y': 0.5}
        active: True 
        '''
        self.sp = Builder.load_string(kvp)
        #self.spinner=MDSpinner()
        self.add_widget(self.sp)
        #self.add_widget(self.spinner)
        self.status = 'fetch'
        self.meta = []
        self.start()

    def createbody(self):
        self.thumb.source = self.meta['id'] + '.jpg'
        self.thumb.reload()
        self.body.add_widget(self.titlebody)
        self.body.add_widget(self.desbody)
        self.body.add_widget(self.downloadbody)
        self.add_widget(self.body)

    def run(self):

        try:
            with youtube_dl.YoutubeDL({}) as ydl:
                y = []
                y.append(self.url)
                self.meta = ydl.extract_info(self.url, download=False)
                print self.meta
                self.title.text = self.meta['title']
                try:
                    self.description.text = self.meta['description']
                except:
                    self.description.text = "NO VIDEO DESCRIPTION FOUND"
                try:
                    import urllib
                    urllib.urlretrieve(self.meta['thumbnail'],
                                       self.meta['id'] + '.jpg')
                except:
                    pass
                self.status = 'fetched'
                self.downloadbutton.disabled = False
                self.downloadbutton.bind(on_press=self.download)
                self.remove_widget(self.sp)
                self.createbody()
                self.createmenu()
                try:
                    for x in self.meta['requested_formats']:
                        print x['format']
                except:
                    for x in self.meta['formats']:
                        print x['format']

                return 0
        except Exception as e:
            print e.message
            self.description.text = 'Please check url and reenter'
            self.title.text = 'INVALID URL'
            self.status = 'error fetch'
            self.clear_widgets()
            self.errorlay = FloatLayout()
            self.dismiss = MDFloatingActionButton(icon='close-circle',
                                                  pos_hint={
                                                      'center_x': 0.5,
                                                      'center_y': 0.5
                                                  })
            self.errortitle = (MDLabel(align='center',
                                       font_style='Title',
                                       text='Failed to Fetch',
                                       pos_hint={
                                           'center_x': 0.5,
                                           'center_y': 0.2
                                       }))
            self.errorlay.add_widget(self.dismiss)
            self.errorlay.add_widget(self.errortitle)
            self.add_widget(self.errorlay)
            self.dismiss.bind(on_press=self.dell)

    def dell(self, instance):
        self.parent.remove_widget(self)

    def downloadthread(self):
        self.downloadbutton.disabled = True
        with youtube_dl.YoutubeDL({'progress_hooks':
                                   [self.progressbarupdate]}) as ydl:
            ydl.download([self.url])
            return 0

    def progressbarupdate(self, d):
        try:
            percentage = (float(d['downloaded_bytes']) /
                          d['total_bytes']) * 100
        except:
            for x in d:
                print x, d[x]
            percentage = (float(d['downloaded_bytes']) /
                          d['total_bytes_estimate']) * 100
        print('updating', percentage)
        self.probar.max = 100
        self.probar.value = percentage
        if d['status'] == 'finished':
            import os
            import shutil
            self.status = 'completed'
            print os.listdir('./')
            x = os.listdir('./')
            for y in x:
                if y.find('.mp4') >= 0:
                    print 'moving'
                    shutil.copy('./' + y, defaultlocation + y)
                    os.remove('./' + y)

    def download(self, instance):
        self.status = 'download'
        self.dt = Thread(target=self.downloadthread)
        self.dt.start()

    def createmenu(self):
        items = ['3gp', 'mp4', 'webm', 'mkv']
        self.formatbuttons = {}
        self.list = MDList()
        for x in items:
            self.formatbuttons[x] = MDFlatButton(text=x)
            self.list.add_widget(self.formatbuttons[x])
        self.formatbut = dropdownmb(text='mp4')
        self.formatbut.bind(on_press=self.show_list)
        self.formatbut.pos_hint = {'center_x': 0.5, 'center_y': 0.6}
        self.controllay = FloatLayout()
        self.controllay.add_widget(self.formatbut)
        #self.desbody.add_widget(self.controllay)
    def show_list(self, instance):
        instance.parent.add_widget(self.list)
        self.list.pos = instance.pos
コード例 #8
0
class TestApp(App):
    def __init__(self, **kwargs):
        super(TestApp, self).__init__(**kwargs)
        self.load_popup = LoadPopup()
        self.load_popup.bind(on_dismiss=self.load_data)
        self.data = None
        self.x_dropdown = None
        self.y_dropdown = None
        self.x_cols = []
        self.y_cols = []

    def load_data(self, event):
        try:
            self.data.head()
        except Exception:
            return 0
        print(self.data.head())  # Testing
        cols = self.data.columns
        self.x_cols = []
        if self.x_dropdown:
            self.x_btn.unbind(on_release=self.x_dropdown.open)
        del self.x_dropdown
        self.x_dropdown = DropDown(dismiss_on_select=False)
        for col in cols:
            btn = ToggleButton(text=col, size_hint_y=None, height=44)
            btn.bind(on_release=lambda btn: self.x_dropdown.select(btn.text))
            self.x_dropdown.add_widget(btn)
        self.x_btn.bind(on_release=self.x_dropdown.open)
        self.x_dropdown.bind(on_select=self.select_xcol)

        self.y_cols = []
        if self.y_dropdown:
            self.y_btn.unbind(on_release=self.y_dropdown.open)
        del self.y_dropdown
        self.y_dropdown = DropDown(dismiss_on_select=False)
        for col in cols:
            btn = ToggleButton(text=col, size_hint_y=None, height=44)
            btn.bind(on_release=lambda btn: self.y_dropdown.select(btn.text))
            self.y_dropdown.add_widget(btn)
        self.y_btn.bind(on_release=self.y_dropdown.open)
        self.y_dropdown.bind(on_select=self.select_ycol)

    def select_xcol(self, event, col):
        if col in self.x_cols:
            self.x_cols.remove(col)
        else:
            self.x_cols.append(col)

    def select_ycol(self, event, col):
        if col in self.y_cols:
            self.y_cols.remove(col)
        else:
            self.y_cols.append(col)

    def build(self):
        fig, ax = plt.subplots(figsize=(8, 3.9))
        self.filename = (self.user_data_dir + "/test.png")
        plt.plot([1, 2, 3], [1, 2, 3])
        plt.savefig(self.filename)
        plt.clf()  # cla for multiple subplots

        layout = GridLayout(rows=3, padding=[0, 0, 0, -1])

        # grid on top 1 row
        self.top_grid = GridLayout(cols=5,
                                   size_hint_y=(.15),
                                   padding=[0, 0, 0, -1])
        # Button for loading data
        load_btn = Button(text="Load Data")
        load_btn.bind(on_press=self.load)
        self.top_grid.add_widget(load_btn)

        # Button for setting x column
        self.x_btn = Button(text="x column")
        self.top_grid.add_widget(self.x_btn)

        # Button for setting y column multi-line selection
        self.y_btn = Button(text="y column")
        self.top_grid.add_widget(self.y_btn)

        # Button for plotting

        self.plot_btn = Button(text="Plot it")
        self.plot_btn.bind(on_press=self.plot)
        self.top_grid.add_widget(self.plot_btn)

        # Button for

        layout.add_widget(self.top_grid)

        self.img = AsyncImage(source=self.filename, nocache=True)
        layout.add_widget(self.img)

        # grid on bottom 1 row
        self.bottom_grid = GridLayout(cols=5,
                                      size_hint_y=(.15),
                                      padding=[0, 0, 0, -1])

        # Button for share button

        # Button for color scheme

        layout.add_widget(self.bottom_grid)

        # self.btn = Button(
        #     text='change',
        #     size_hint=(None, None))
        # self.btn.bind(on_press=self.callback)
        # layout.add_widget(self.btn)

        return layout

    def load(self, event):
        if self.x_dropdown:
            self.x_dropdown.dismiss()
        if self.y_dropdown:
            self.y_dropdown.dismiss()
        self.load_popup.open()

    def plot(self, event):
        try:
            X = self.data[self.x_cols]
            y = self.data[self.y_cols]
            plt.plot(X, y)
            plt.legend()
            plt.savefig(self.filename)
            plt.clf()  # cla for multiple subplots
            self.img.source = self.filename
            self.img.reload()
        except Exception:
            # Open error popup here with descriptor
            print("Bad plot")
コード例 #9
0
ファイル: MainApp.py プロジェクト: hamik112/AutoInterface
class CameraScreen(Screen):
    
    def __init__(self, **kwargs):
        super(CameraScreen, self).__init__(**kwargs)
        
        self.Background = Image(source='Images/BG_Empty.png',
                                pos=(0, 0),
                                size_hint=(None, None),
                                size=(800, 480))
        
        self.CameraImage = AsyncImage(source='http://www.thruway.ny.gov/webcams/captures/img4ni00144n.jpg?%s.jpg' % uuid4().hex,
                                  pos=(10, 10),
                                  allow_stretch=True,
                                  nocache=True,
                                  size_hint=(None, None),
                                  size=(780, 415))
        
        self.CaptureImageButton = Button(text='Capture Image',
                                    pos=(130, 430),
                                    size_hint=(None, None),
                                    size=(110, 40),
                                    background_color=(0.1, 0.1, 0.1, 0.75))
        self.CaptureImageButton.bind(on_press=self.CaptureImage)
        
        self.CaptureVideoButton = Button(text='Capture Video',
                                    pos=(250, 430),
                                    size_hint=(None, None),
                                    size=(110, 40),
                                    background_color=(0.1, 0.1, 0.1, 0.75))
        self.CaptureVideoButton.bind(on_press=self.CaptureVideo)
        
        self.CaptureTimelapseButton = Button(text='Capture Timelapse',
                                    pos=(370, 430),
                                    size_hint=(None, None),
                                    size=(110, 40),
                                    background_color=(0.1, 0.1, 0.1, 0.75))
        self.CaptureTimelapseButton.bind(on_press=self.CaptureTimelapse)
        
        self.LiveButton = ToggleButton(text='IMAGE',
                                    pos=(490, 430),
                                    size_hint=(None, None),
                                    size=(110, 40),
                                    background_color=(0.1, 0.1, 0.1, 0.75))
        self.LiveButton.bind(on_press=self.StartCam)
        
        self.ExitButton = Button(text='Exit',
                                 pos=(690, 430),
                                 size_hint=(None, None),
                                 size=(100, 40),
                                 background_color=(0.9, 0.0, 0.0, 0.75))
        self.ExitButton.bind(on_press=self.exitApplication)
        
        self.BackButton = Button(text='Back',
                                 pos=(10, 430),
                                 size_hint=(None, None),
                                 size=(100, 40),
                                 background_color=(0.18, 0.38, 0.70, 0.75))
        self.BackButton.bind(on_press=self.BackToMenu)
        
        
        #CAMERA CONTROL VARIABLES
        self.CameraStarted = False
        #self.UpdateThread = Thread(target=self.CamUpdate)
        self.CameraUpdateEvent = None
        
        # Add all Components to Screen
        self.add_widget(self.Background)
        self.add_widget(self.CameraImage)
        self.add_widget(self.CaptureImageButton)
        self.add_widget(self.CaptureVideoButton)
        self.add_widget(self.CaptureTimelapseButton)
        self.add_widget(self.ExitButton)
        self.add_widget(self.BackButton)
        self.add_widget(self.LiveButton)
    
    def exitApplication(self, *args):
        App.get_running_app().stop() 
        
    def BackToMenu(self, *args):
        sm.current = 'menu'    
    
    def StartCam(self, *args):
        #source = 'https://i.ytimg.com/vi/rRlHBeg7KoU/maxresdefault.jpg'
        #print(source)
        self.CameraStarted = not self.CameraStarted
        
        """
        if(self.CameraStarted == True and not self.UpdateThread.isAlive()):
            self.UpdateThread.start()
        """
        
        if(self.CameraStarted == True):
            self.LiveButton.text='LIVE'
            self.CameraUpdateEvent = Clock.schedule_interval(self.CamUpdate,4)
            
        else:
            self.LiveButton.text='IMAGE'
            self.CameraUpdateEvent.cancel()
        
    def CaptureImage(self, *args):
        pass
    
    def CaptureVideo(self, *args):
        pass
        
    def CaptureTimelapse(self, *args):
        pass
        
    def CamUpdate(self, *args):
        if(self.CameraStarted):
            self.CameraImage.reload()
コード例 #10
0
class Container(FloatLayout):
    def __init__(self, *args, **kwargs):

        super(Container, self).__init__(*args, **kwargs)
        self.main_screen()
        self.code = ""
        self.function_dict = {}

    def main_screen(self):
        self.main_grid = GridLayout(cols=1,
                                    size_hint=(.3, .7),
                                    pos_hint={
                                        "right": 0.32,
                                        "top": .75
                                    })
        self.clear_widgets()
        self.load_btn = Button(text="Load",
                               size_hint=(.3, .2),
                               pos_hint={
                                   "right": 0.32,
                                   "top": .75
                               })

        self.load_btn.bind(on_press=self.load_pop_up)

        self.main_grid.add_widget(self.load_btn)
        self.analysis_btn = Button(text="Analysis",
                                   size_hint=(.3, .2),
                                   pos_hint={
                                       "right": 0.32,
                                       "top": .53
                                   })
        self.analysis_btn.bind(on_press=self.main_analysis)

        self.main_grid.add_widget(self.analysis_btn)

        self.recursive_analysis_btn = Button(text="Recursive\nAnalysis",
                                             size_hint=(.3, .2),
                                             pos_hint={
                                                 "right": 0.32,
                                                 "top": .53
                                             })
        self.recursive_analysis_btn.bind(on_press=self.main_recursive_analysis)

        self.main_grid.add_widget(self.recursive_analysis_btn)

        self.graph_btn = Button(text="Function\nTest",
                                size_hint=(.3, .2),
                                pos_hint={
                                    "right": 0.32,
                                    "top": .31
                                })
        self.graph_btn.bind(on_press=self.graph_pop_up)

        self.main_grid.add_widget(self.graph_btn)

        self.terminal_btn = Button(text="Terminal",
                                   size_hint=(.3, .2),
                                   pos_hint={
                                       "right": 0.32,
                                       "top": .31
                                   })
        self.terminal_btn.bind(on_press=self.main_terminal)

        self.main_grid.add_widget(self.terminal_btn)

        self.add_widget(self.main_grid)
        try:
            g_logo_path = "https://github.com//weriko/complexityAnalysis/raw/master/Logo.PNG"

            self.logo_btn = AsyncImage(source=g_logo_path,
                                       size_hint=(.7, .2),
                                       pos_hint={
                                           "right": 0.75,
                                           "top": .98
                                       })
            self.add_widget(self.logo_btn)
        except:

            try:
                self.logo_btn = kvImage(pos_hint={
                    "right": 0.75,
                    "top": .98
                },
                                        allow_stretch=True,
                                        keep_ratio=True,
                                        size_hint=(.7, .2))

                self.logo_btn.source = "data/Logo.png"
                self.logo_btn.reload()
                self.add_widget(self.logo_btn)
            except Exception as e:
                print(e)

        self.dropdown_btn = Button(text="""
               __
               __  
               __
                                  """,
                                   font_size=30,
                                   size_hint=(.2, .2),
                                   background_color=(0, 0, 0, 0),
                                   pos_hint={
                                       "right": 0.95,
                                       "top": .98
                                   })
        self.add_widget(self.dropdown_btn)
        self.dropdown_btn.bind(on_press=self.help_pop_up)

        self.scrollable_code = ScrollView(size_hint=(.55, 0.64),
                                          pos_hint={
                                              "right": 0.95,
                                              "top": 0.75
                                          })
        self.grid_widget_code = GridLayout(cols=1, size_hint=(1, None))
        self.grid_widget_code.bind(
            minimum_height=self.grid_widget_code.setter('height'))

        self.scrollable_code.add_widget(self.grid_widget_code)
        self.add_widget(self.scrollable_code)

        try:
            if self.code:
                for i in self.code.split("\n"):
                    self.grid_widget_code.add_widget(
                        TextInput(text=str(i),
                                  size_hint_y=None,
                                  readonly=True,
                                  foreground_color=(1, 1, 1, 1),
                                  background_color=(0, 0, 0, 1)))
        except:
            pass

    def run_terminal(self, k):  #Executes the code inside terminal

        try:

            self.terminal_output.foreground_color = (0, 0, 0, 1)
            f = open("console.out", "w")
            sys.stdout = f

            exec(self.terminal_input.text, locals())
            sys.stdout = sys.__stdout__
            f.close()

            out = open("console.out", "r").read()

            self.terminal_output.text += out
        except Exception as e:
            """
            show = Label(text="Please check your code!")
            popup = Popup(title='Menu',
                        content=show,
                        size_hint=(None, None), size=(int(screensize[1]/1.5),int(screensize[0]/1.5)))
            """
            self.terminal_output.text += f"ERROR\nPlease check your code!\n{e}\n"
            self.terminal_output.foreground_color = (1, 0, 0, 1)

    def open_terminal_code_run(self, popup):
        try:
            f = open(f"savefiles/{self.open_code_name_input.text}", "r")
            self.terminal_input.text = f.read()
            f.close()
            popup.dismiss()
        except:
            self.terminal_output.text += "File not found\n"
            popup.dismiss()

    def open_terminal_code(self, k):

        show = GridLayout(cols=1)
        self.open_code_name_input = TextInput(text="Untitled.py")
        popup = Popup(title='Save',
                      content=show,
                      size_hint=(None, None),
                      size=(int(screensize[1] / 2.5),
                            int(screensize[0] / 1.5)))
        open_code_btn = Button(text="""Open""",
                               size_hint=(.2, .2),
                               pos_hint={
                                   "right": 0.55,
                                   "top": .25
                               })
        open_code_btn.bind(
            on_press=lambda x: self.open_terminal_code_run(popup))

        show.add_widget(self.open_code_name_input)

        show.add_widget(open_code_btn)

        popup.open()

    def save_terminal_code_run(self, popup):
        try:
            os.mkdir("savefiles")
        except:
            pass
        f = open(f"savefiles/{self.save_code_name_input.text}", "w")
        f.write(self.terminal_input.text)
        f.close()
        popup.dismiss()

    def save_terminal_code(self, k):

        show = GridLayout(cols=1)
        self.save_code_name_input = TextInput(text="Untitled.py")
        save_code_btn = Button(text="""Save""",
                               size_hint=(.2, .2),
                               pos_hint={
                                   "right": 0.55,
                                   "top": .25
                               })
        popup = Popup(title='Save',
                      content=show,
                      size_hint=(None, None),
                      size=(int(screensize[1] / 2.5),
                            int(screensize[0] / 1.5)))
        save_code_btn.bind(
            on_press=lambda x: self.save_terminal_code_run(popup))

        show.add_widget(self.save_code_name_input)

        show.add_widget(save_code_btn)

        popup.open()

    def export_terminal_analysis(self):
        self.code = self.terminal_input.text
        self.main_screen()

    def open_github_terminal_code_run(self, popup):
        try:
            url = self.open_github_code_name_input.text
            rq = requests.get(url)
            if rq.status_code == requests.codes.ok:
                content = rq.content.decode()

            else:
                print('Content was not found.')
            self.terminal_input.text = content
            popup.dismiss()

        except:
            self.terminal_output.text += "ERROR\nFile not found"
            popup.dismiss()

    def open_github_terminal_code(self, k):

        show = GridLayout(cols=1)
        self.open_github_code_name_input = CTextInput(text="Raw")
        open_github_code_btn = Button(text="""Open""",
                                      size_hint=(.2, .2),
                                      pos_hint={
                                          "right": 0.55,
                                          "top": .25
                                      })
        popup = Popup(title='Save',
                      content=show,
                      size_hint=(None, None),
                      size=(int(screensize[1] / 2.5),
                            int(screensize[0] / 1.5)))
        open_github_code_btn.bind(
            on_press=lambda x: self.open_github_terminal_code_run(popup))

        show.add_widget(self.open_github_code_name_input)

        show.add_widget(open_github_code_btn)

        popup.open()

    def main_terminal(self, k):
        self.clear_widgets()
        run_btn = Button(text="""Run""",
                         size_hint=(.15, .15),
                         pos_hint={
                             "right": 0.945,
                             "top": .25
                         })

        run_btn.bind(on_press=self.run_terminal)

        open_btn = Button(text="""Open""",
                          size_hint=(.15, .15),
                          pos_hint={
                              "right": 0.795,
                              "top": .25
                          })
        open_btn.bind(on_press=self.open_terminal_code)

        open_btn_github = Button(text="""Open\ngithub""",
                                 size_hint=(.15, .15),
                                 pos_hint={
                                     "right": 0.345,
                                     "top": .25
                                 })
        open_btn_github.bind(on_press=self.open_github_terminal_code)

        save_btn = Button(text="""Save""",
                          size_hint=(.15, .15),
                          pos_hint={
                              "right": 0.645,
                              "top": .25
                          })
        save_btn.bind(on_press=self.save_terminal_code)

        analyze_btn = Button(text="""Analyze""",
                             size_hint=(.15, .15),
                             pos_hint={
                                 "right": 0.495,
                                 "top": .25
                             })
        analyze_btn.bind(on_press=lambda x: self.export_terminal_analysis())

        back_btn = Button(text="""Back""",
                          size_hint=(.15, .15),
                          pos_hint={
                              "right": 0.195,
                              "top": .25
                          })
        back_btn.bind(on_press=lambda x: self.main_screen())

        try:
            a = self.terminal_input.text
        except:

            self.terminal_input = CTextInput(text="",
                                             size_hint=(.87, .50),
                                             pos_hint={
                                                 "right": 0.93,
                                                 "top": .98
                                             })
            self.terminal_output = CTextInput(text="",
                                              size_hint=(.87, .20),
                                              pos_hint={
                                                  "right": 0.93,
                                                  "top": .48
                                              })
        self.add_widget(self.terminal_output)
        self.add_widget(self.terminal_input)

        self.add_widget(analyze_btn)
        self.add_widget(run_btn)
        self.add_widget(open_btn_github)
        self.add_widget(open_btn)
        self.add_widget(save_btn)
        self.add_widget(back_btn)

    def recursive_function(self, func):
        func = func.text

        index = self.functions.index(func)
        print(index)

        #print(self.functions_helper[index])
        exec(self.functions_helper[index], locals())

        times = []

        complexity = self.analyze_recursion(self.functions_helper[index])
        for n in range(1, 101):
            times.append(eval(complexity[0] + "* n**" + str(complexity[1])))

        plt.plot(range(1, 101), times)
        plt.ylabel("Time")

        plt.savefig("temp.png")

        plt.close()

        self.aimg2.source = "temp.png"
        self.aimg2.reload()

    def main_recursive_analysis(self, k):
        self.clear_widgets()
        self.scrollable_numeric = ScrollView(size_hint=(.96, 0.45),
                                             pos_hint={
                                                 "right": 0.98,
                                                 "top": 0.48
                                             })
        show = GridLayout(cols=2, size_hint_y=None)
        show.bind(minimum_height=show.setter('height'))
        self.test_functions()

        self.function_texts = []

        for i in self.functions:

            btn = Button(
                text=str(i),
                size_hint_y=None,
                height=screensize[1] / 4,
            )

            btn.bind(on_press=self.recursive_function)
            show.add_widget(btn)

            self.function_texts.append(i)

        self.aimg2 = kvImage(pos_hint={
            "right": 0.95,
            "top": 0.96
        },
                             allow_stretch=True,
                             keep_ratio=True,
                             size_hint_y=.45,
                             size_hint_x=.9)
        self.add_widget(self.aimg2)

        btn2 = Button(
            text="Back",
            size_hint_y=None,
            height=screensize[1] / 4,
        )
        btn2.bind(on_press=lambda x: self.main_screen())

        self.scrollable_numeric.add_widget(show)
        show.add_widget(btn2)
        self.add_widget(self.scrollable_numeric)

    def exec_function(self, func):
        index = self.functions.index(func.text)
        #print(index)
        print(index)
        print(self.functions_helper)
        print(len(self.functions_helper))
        function_def = self.functions_helper[index]
        try:

            func = func.text
            #print(self.functions)
            #print(self.functions_helper)

            print(function_def)
            #print(self.functions_helper[index])
            function_name = self.get_function_name(self.functions[index])
            function_name = function_name[:function_name.index("(")]
            #function_name = f"global {function_name}\n" + function_def

            print(function_name)
            exec(function_def, locals())

            times = []
            rng = self.function_range[index].text.split(",")
            function = self.function_texts[index].text.replace("x", "i")

            for i in range(int(rng[0]), int(rng[1]), int(rng[2])):
                s = time.time()

                exec(function, locals())
                times.append(time.time() - s)

            plt.plot(range(int(rng[0]), int(rng[1]), int(rng[2])), times)
            plt.ylabel("Time")

            plt.savefig("temp.png")

            plt.close()

            self.aimg2.source = "temp.png"
            self.aimg2.reload()
        except Exception as e:
            #print(e)
            show = GridLayout(cols=1)
            label = Label(
                text=
                "ERROR\nCheck your range input\nOnly x can be a non constant argument!\n--> f(x,5,3)\nIt is possible for max recursion depth\nto be reached"
            )
            popup = Popup(title='Menu',
                          content=show,
                          size_hint=(None, None),
                          size=(int(screensize[1] / 2.5),
                                int(screensize[0] / 1.5)))

            show.add_widget(label)

            popup.open()

    def help_pop_up(self, k):
        show = GridLayout(cols=1)
        self.button_about = Button(text="About", )
        self.button_help = Button(text="Help")

        show.add_widget(self.button_about)
        show.add_widget(self.button_help)

        self.button_about.bind(on_press=self.load_about_us_pop_up)
        self.button_help.bind(on_press=self.open_browser_help)
        try:
            self.help_popup.dismiss()
        except:
            pass
        self.help_popup = Popup(title='Menu',
                                content=show,
                                size_hint=(None, None),
                                size=(int(screensize[1] / 2.5),
                                      int(screensize[0] / 1.5)))
        self.help_popup.open()

    def open_browser_help(self, k):
        try:
            webbrowser.open(
                'https://github.com/weriko/complexityAnalysis/blob/master/guiaEN.pdf',
                new=2)
        except:

            popup = Popup(title='ERROR',
                          content=Label(text="CONNECTION ERROR"))
            popup.open()

    def load_about_us_pop_up(self, k):
        grid = GridLayout(cols=1)
        about_label = Label(
            text="https://github.com/weriko\nhttps://github.com/AndresYT",
            font_size=30)
        button_back = Button(text="back")
        button_back.bind(on_press=self.help_pop_up)
        grid.add_widget(about_label)
        grid.add_widget(button_back)
        self.help_popup.content = grid
        self.help_popup.size = (int(screensize[1] / 2.5),
                                int(screensize[0] / 1.5))

    def graph_help(self, k):
        show = GridLayout(cols=1)
        help_label = TextInput(text="""Input:\n
                           First field -> name_of_function(x,args). There can only be one argument varying, and that should be x. Every other argument should be a constant\n
                           Second field -> START,END,STEP  ,The range in which x will be tested"""
                               )
        back_button = Button(text="back")
        self.graph_help_popup = Popup(title='Menu',
                                      content=show,
                                      size_hint=(None, None),
                                      size=(int(screensize[1] / 2.5),
                                            int(screensize[0] / 1.5)))
        show.add_widget(help_label)
        show.add_widget(back_button)
        back_button.bind(on_press=self.graph_help_popup.dismiss)

        self.graph_help_popup.open()

    def graph_pop_up(self, k):
        self.clear_widgets()
        self.scrollable_numeric = ScrollView(size_hint=(.96, 0.45),
                                             pos_hint={
                                                 "right": 0.98,
                                                 "top": 0.48
                                             })
        show = GridLayout(cols=3, size_hint_y=None)
        show.bind(minimum_height=show.setter('height'))

        self.test_functions()

        self.function_texts = []
        self.function_range = []

        for i in self.functions:

            btn = Button(text=str(i),
                         size_hint_y=None,
                         height=screensize[1] / 4)

            btn.bind(on_press=self.exec_function)
            show.add_widget(btn)

            temp = TextInput(text=self.get_function_name(str(i)),
                             size_hint_y=None,
                             height=screensize[1] / 4,
                             foreground_color=(1, 1, 1, 1),
                             background_color=(0, 0, 0, 1))
            temp2 = TextInput(text="0,10,1",
                              size_hint_y=None,
                              foreground_color=(1, 1, 1, 1),
                              height=screensize[1] / 4,
                              background_color=(0, 0, 0, 1))
            self.function_texts.append(temp)
            self.function_range.append(temp2)
            show.add_widget(temp)
            show.add_widget(temp2)
        btn = Button(
            text="Help",
            size_hint_y=None,
            height=screensize[1] / 4,
        )

        btn.bind(on_press=self.graph_help)
        show.add_widget(btn)
        self.aimg2 = kvImage(pos_hint={
            "right": 0.95,
            "top": 0.96
        },
                             allow_stretch=True,
                             keep_ratio=True,
                             size_hint_y=.45,
                             size_hint_x=.9)
        self.add_widget(self.aimg2)

        btn2 = Button(
            text="Back",
            size_hint_y=None,
            height=screensize[1] / 4,
        )
        btn2.bind(on_press=lambda x: self.main_screen())

        show.add_widget(btn2)

        self.scrollable_numeric.add_widget(show)
        self.add_widget(self.scrollable_numeric)
        #self.answers_popup = Popup(title="Resultados",content=show)
        #self.answers_popup.open()

    def delete_input_text(self, k, p):

        deleatable_list = ["Raw github link", "Path"]
        if k.text in deleatable_list:
            k.text = ""

    def load_pop_up(self, k):
        show = GridLayout(cols=1)
        btn_github = Button(text="Load from Github")

        btn_github.bind(on_press=self.load_github)
        self.github_code_rd = CTextInput(text="Raw github link",
                                         size_hint_y=None,
                                         foreground_color=(1, 1, 1, 1),
                                         background_color=(0, 0, 0, 1))
        self.github_code_rd.bind(on_touch_down=self.delete_input_text)

        btn = Button(text="Back", )
        btn.bind(on_press=lambda x: self.answers_popup.dismiss())
        btn_path_load = Button(text="Load from Path")

        btn_path_load.bind(on_press=self.load_path)
        self.path_code_rd = CTextInput(text="Path",
                                       size_hint_y=None,
                                       foreground_color=(1, 1, 1, 1),
                                       background_color=(0, 0, 0, 1))
        self.path_code_rd.bind(on_touch_down=self.delete_input_text)

        show.add_widget(self.github_code_rd)
        show.add_widget(btn_github)
        show.add_widget(self.path_code_rd)
        show.add_widget(btn_path_load)
        show.add_widget(btn)
        self.answers_popup = Popup(title="Resultados", content=show)
        self.answers_popup.open()

    def get_tabs(self, line):
        tabs = 0
        for i in line:
            if i == " ":
                tabs += 1
            else:
                break
        return tabs

    def check_alpha(self, x):
        for i in x:

            if i.isalnum():
                return True
        return False

    def get_function_name(self, function):
        for i in function.split("\n"):
            if "def" in i:
                func_name = i
                break

        func_name = func_name.split(" ")[1]
        return func_name.replace(":", "")

    def get_functions(self):
        func_tabs = 0
        func = []
        total_func = []
        for line in self.code.split("\n"):
            if "def" in line and self.get_tabs(line) <= func_tabs:
                if func != []:  # If func is not an empty list, append to total_func
                    total_func.append(func)
                func = [line]  #Starts the list with the current line
                func_tabs = self.get_tabs(
                    line
                )  #this is the amount of lines in the definition of funtion
                continue  #If it finds a def, it gets all the lines inside the def
            if self.get_tabs(line) > func_tabs or (
                    lambda s: any([c.isalnum() for c in s], line)):
                func.append(
                    line
                )  #If the number of indentations is higher than the definition, it adds the line to the list, othewise it stops
            else:
                total_func.append(func)
                func = []
        if func != []:
            total_func.append(func)
        return list(
            filter(lambda s: any([self.check_alpha(c) for c in s]),
                   total_func))

    def analyze_recursion_helper(self, line, func_name):
        if "(" not in line:
            return 0
        op = 0
        flag = 0
        counter = 0
        helper = []

        for i in range(len(line)):

            if line[i] == "(":
                op += 1
                start = i
                flag = 1
            if line[i] == ")":
                op -= 1
            if op == 0 and flag:
                helper.append((start, counter))
                op = 0
                flag = 0
                counter = 0
            if op != 0:
                counter += 1
        #print(helper)
        a = len(helper)
        b_list = []
        for i in [line[x[0]:x[0] + x[1]] for x in helper]:
            #print(i)
            temp = ""

            for j in i:

                if j.isdigit():
                    temp += j
                else:
                    b_list.append(temp)
                    temp = ""
            b_list.append(temp)

        try:
            b = max([int(x) for x in b_list if x.isdigit()])
        except:
            b = 0

        if a >= 1 and b == 0:
            return "inf"
        elif a >= 2:
            return f"{a}**n"
        elif a == 0:
            return "1"
        elif a == b and "/" in line and b != 1:
            return f"n*log(n)"
        elif "/" in line:
            return f"log(n)"

        else:
            return f"n"

    def analyze_recursion(self, function):

        for i in function.split("\n"):
            if "def" in i:
                func_name = i
                break

        func_name = func_name.split(" ")[1]
        string = ""
        for i in func_name:
            if i != "(":
                string += i
            else:

                break
        func_lines = [x for x in function.split("\n") if string in x]
        complexities = []
        for i in func_lines[1:]:

            complexities.append(self.analyze_recursion_helper(i, string))

        mx = "1"
        flag = 0
        for i in complexities:
            if i == "inf":
                mx = "inf"
                break
            if "**n" in str(i):
                mx = i
                flag = 3
            if i == "n*log(n)" and flag < 3:
                mx = i
                flag = 2
            if i == "log(n)" and flag < 2:
                mx = i
                flag = 1
            if i == "n":
                mx = "n"
        #print(mx)
        loops = self.get_instructions(code=function)
        loops = self.get_loops(code=loops)
        #print(loops)
        return mx, loops

    def test_functions(self):

        code = self.code.split("\n")
        self.functions = [x for x in code if "def" in x]

        helper_helper = self.get_functions()
        helper_helper_helper = []
        for i in helper_helper:
            #print(i)
            helper_helper_helper.append(["".join(x + "\n") for x in i])
        #print(helper_helper_helper)
        helper_helper_helper_helper = []

        self.functions_helper = ["".join(x) for x in helper_helper_helper]
        #print(self.functions_helper,"\naaaa")

    def load_github(self, instance):
        try:
            url = self.github_code_rd.text
            rq = requests.get(url)
            if rq.status_code == requests.codes.ok:
                content = rq.content.decode()

            else:
                print('Content was not found.')
            self.code = content
            self.grid_widget_code.clear_widgets()
            for i in self.code.split("\n"):
                self.grid_widget_code.add_widget(
                    TextInput(text=str(i),
                              size_hint_y=None,
                              readonly=True,
                              foreground_color=(1, 1, 1, 1),
                              background_color=(0, 0, 0, 1)))
            self.answers_popup.dismiss()
        except:
            self.answers_popup.dismiss()

    def load_path(self, instance):
        try:
            content = open(self.path_code_rd.text).read()
            self.code = content
            self.grid_widget_code.clear_widgets()
            for i in self.code.split("\n"):
                self.grid_widget_code.add_widget(
                    TextInput(text=str(i),
                              size_hint_y=None,
                              readonly=True,
                              foreground_color=(1, 1, 1, 1),
                              background_color=(0, 0, 0, 1)))
            self.answers_popup.dismiss()
        except:
            self.answers_popup.dismiss()

    def get_instructions(self, code=None):
        if code:  #If code is passed as an argument, it uses that code instead of the one saved in object variable and returns the instructions for the code passed as argument
            with StringIO() as out:
                dis.dis(code, file=out)
                datatemp = out.getvalue()

                data = datatemp.split("\n")
            code_data = [list(re.split(r'\s{3,}', x)) for x in data]
            code_instructions = [x[10:] for x in data]
            #print(self.code_instructions)
            return code_instructions

        with StringIO() as out:
            dis.dis(self.code, file=out)
            datatemp = out.getvalue()

            data = datatemp.split("\n")
        self.code_data = [list(re.split(r'\s{3,}', x)) for x in data]
        self.code_instructions = [x[10:] for x in data]
        #print(self.code_instructions)
        return datatemp

    def get_loops(self, code=None):
        #If code is passed as an argument, it uses that code instead of the one saved in object variable and returns the analysis for the code passed as argument
        mx = 0
        curr = 0

        print(sys.version_info)
        op_code = "GET_ITER" if float(sys.version[:3]) >= 3.8 else "SETUP_LOOP"
        #print(op_code)

        if code:
            for i in code:
                if op_code in i:
                    curr += 1

                if "JUMP_ABSOLUTE" in i:
                    if curr > mx:
                        mx = curr
                    curr = 0
        else:

            for i in self.code_instructions:
                if op_code in i:
                    curr += 1

                if "JUMP_ABSOLUTE" in i:
                    if curr > mx:
                        mx = curr
                    curr = 0

        return mx
        #C:/Users/Santiago/Desktop/Uni/4 semestre/Algoritmos/bunzei/supertemp.py

    def main_analysis(self, k):

        self.clear_widgets()
        self.scrollable_dis = ScrollView(size_hint=(.55, 0.9),
                                         pos_hint={
                                             "right": 0.98,
                                             "top": 0.95
                                         })
        self.grid_widget_dis = GridLayout(cols=1, size_hint=(1, None))
        self.grid_widget_dis.bind(
            minimum_height=self.grid_widget_dis.setter('height'))

        self.scrollable_dis.add_widget(self.grid_widget_dis)
        self.add_widget(self.scrollable_dis)
        datatemp = self.get_instructions()
        for i in datatemp.split("\n"):
            self.grid_widget_dis.add_widget(
                TextInput(text=str(i),
                          size_hint_y=None,
                          readonly=True,
                          foreground_color=(1, 1, 1, 1),
                          background_color=(0, 0, 0, 1)))
        cmplx = self.get_loops()
        self.complexity_output = TextInput(text=str("O(n^" + str(cmplx) + ")"),
                                           foreground_color=(1, 1, 1, 1),
                                           background_color=(0, 0, 0, 1),
                                           font_size=20,
                                           size_hint=(0.1, 0.05),
                                           pos_hint={
                                               "right": 0.3,
                                               "top": 0.95
                                           })
        self.add_widget(self.complexity_output)
        x = list(range(0, 1000))
        y, x = zip(*[((i / 10)**float(cmplx), i / 10) for i in x])

        #print(cmplx)
        plt.plot(x, y)
        plt.ylabel("Time")

        plt.savefig("temp.png")

        plt.close()
        self.aimg = kvImage(pos_hint={
            "right": 0.42,
            "top": 0.92
        },
                            allow_stretch=True,
                            keep_ratio=True,
                            size_hint_y=.6,
                            size_hint_x=.4)
        self.aimg.source = "temp.png"
        self.aimg.reload()

        self.go_back_btn = Button(text="Back",
                                  size_hint=(.2, .1),
                                  pos_hint={
                                      "right": 0.25,
                                      "top": .2
                                  })

        self.go_back_btn.bind(on_press=lambda x: self.main_screen())
        self.add_widget(self.go_back_btn)
        self.add_widget(self.aimg)
コード例 #11
0
ファイル: litemc.py プロジェクト: Uffik81/pyWink
class LitePlayer(App):
    video = None
    _wink_sdk_ver = ''

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._wink_index = WinkParams('https://wink.rt.ru/', COOKIE)
        self._wink_tv = WinkParams('https://wink.rt.ru/tv', COOKIE)
        self._wink_client = WincClientConnection(params=self._wink_index,
                                                 tv=self._wink_tv)
        self._playlist = self._wink_client.get_tv_playlist()
        self._current_ch = 0

    def build(self):
        Window.bind(on_keyboard=self.on_keyboard)  # bind our handler
        self._list_channels = self._wink_client.get_list_channels()
        ch_url, err = self._wink_client.get_channel_url(
            str(self._list_channels[self._current_ch]
                ['nc_channel_id']))  #self._wink_client._fairplay_cert_url)
        #url_key_1 = 'https://s40757.cdn.ngenix.net/certificates/8BA6D7AC942DE15E1B375DEF7FA20918757A6533'
        #self._wink_client.load_cert_ott(url_key_1)

        self.video = Video(source=ch_url)
        self.video.state = 'play'
        self.video.options = {'eos': 'loop'}
        self.video.allow_stretch = True
        #self.video.pos_hint = {'top': 1.0}
        self._grid_1 = GridLayout(cols=2,
                                  row_force_default=True,
                                  row_default_height=40)
        self._grid_menu = GridLayout(cols=8)
        self._grid_channels = GridLayout(cols=3)

        self.video.add_widget(self._grid_1)
        self.l = Label(text='Hello world',
                       font_size='20sp',
                       size_hint=(1, 0.17))
        #self.l.pos(
        print(self.l.pos)
        self.img1 = AsyncImage(source=self._wink_tv.__IMAGES_URL__ +
                               '/sdp/nc-snapshot1569398092010.jpg',
                               pos_hint={
                                   'x': 0.0,
                                   'y': 0.8
                               })
        self.video.add_widget(self._grid_menu)
        self.video.add_widget(self.img1)
        self.video.add_widget(self.l)
        self._grid_1.add_widget(self._grid_channels)
        self.l_ch = []
        for i in range(5):
            lab1 = Label(text=self._list_channels[i]['name'], font_size='20sp')
            self._grid_channels.add_widget(lab1)
            self.l_ch += [lab1]

        print(Window.size)
        return self.video

    def VideoDone(self, value, value2):
        print("video done", value, value2)

    def _get_utc(self):
        return round(
            (datetime.datetime.now() -
             datetime.datetime(1970, 1, 1)).total_seconds() * 1000) + 338055300

    def get_drm_parse(self):
        root = xmltodict.parse(self._drm_xml)
        _mpd = root['MPD']
        print(_mpd)
        self._baseurl_drm = self._url_drm
        for adaptation_set in _mpd['Period']['AdaptationSet']:
            shab = adaptation_set['SegmentTemplate']
            #print (shab)
            self._drm_shablon = shab['@media']
            for key in adaptation_set['Representation']:
                for inkey in key:
                    if inkey == '@height' and key[inkey] == '1080':
                        self._video_1080 = key['@id']
                    if inkey == '@bandwidth' and key[inkey] == '500000':
                        self._audio_1080 = key['@id']
        _tmp_url = self._baseurl_drm.replace('/manifest.mpd?profile=web_auto',
                                             '/')
        _tmp_utc_str = str(self._get_utc())
        _tmp_url_video = ''.join([
            _tmp_url,
            self._drm_shablon.replace('$RepresentationID$',
                                      self._video_1080).replace(
                                          '$Time$', _tmp_utc_str)
        ])
        print(_tmp_url_video)
        _tmp_url_audio = ''.join([
            _tmp_url,
            self._drm_shablon.replace('$RepresentationID$',
                                      self._audio_1080).replace(
                                          '$Time$', _tmp_utc_str)
        ])

        print(_tmp_url_audio)

    def on_stop(self):
        # The Kivy event loop is about to stop, set a stop signal;
        # otherwise the app window will close, but the Python process will
        # keep running until all secondary threads exit.
        print('stopping and closing kivy')
        #self.video.state='stop'

    def on_keyboard(self, window, key, scancode, codepoint, modifier):
        print(window, key, scancode, codepoint, modifier)
        if key == 13:
            pass
        elif codepoint == 'p':
            print('pausing with p pressed')
            self.video.state = 'stop'
        elif codepoint == 's':
            print('starting with s pressed')
            self.video.state = 'play'
        elif codepoint == 'r':
            #self.video.source=self._wink_client.get_channel_url('5')
            self.video.state = 'play'
            print('re-starting with r pressed')
            self.video.seek(0, precise=True)
        if key == 280:
            self._current_ch += 1
            if self._current_ch > (len(self._list_channels) - 1):
                self._current_ch = 0
            ch_url, err = self._wink_client.get_channel_url(
                str(self._list_channels[self._current_ch]['nc_channel_id']))
            if not err:
                self.img1.source = self._wink_tv.__IMAGES_URL__ + self._wink_client._current_channel[
                    'logo']
                self.img1.reload()
                self.video.source = ch_url
                self.video.state = 'play'
                print('re-starting with r pressed')
                #self.video.seek(0, precise=True)
            self.l.text = self._wink_client._current_channel['description']
        if key == 281:
            self._current_ch -= 1
            if self._current_ch < 0:
                self._current_ch = len(self._list_channels) - 1
            ch_url, err = self._wink_client.get_channel_url(
                str(self._list_channels[self._current_ch]['nc_channel_id']))
            if not err:
                self.img1.source = self._wink_tv.__IMAGES_URL__ + self._wink_client._current_channel[
                    'logo']
                self.img1.reload()
                self.video.source = ch_url
                self.video.state = 'play'
                print('re-starting with r pressed')
                #self.video.seek(0, precise=True)
            self.l.text = self._wink_client._current_channel['description']
        else:
            print(key)