Exemplo n.º 1
0
    def _mainloop(self):
        EventLoop.idle()

        for event in pygame.event.get():

            # kill application (SIG_TERM)
            if event.type == pygame.QUIT:
                EventLoop.quit = True
                self.close()

            # mouse move
            elif event.type == pygame.MOUSEMOTION:
                # don't dispatch motion if no button are pressed
                if event.buttons == (0, 0, 0):
                    continue
                x, y = event.pos
                self.dispatch('on_mouse_move', x, y, self.modifiers)

            # mouse action
            elif event.type in (pygame.MOUSEBUTTONDOWN,
                                pygame.MOUSEBUTTONUP):
                self._pygame_update_modifiers()
                x, y = event.pos
                btn = 'left'
                if event.button == 3:
                    btn = 'right'
                elif event.button == 2:
                    btn = 'middle'
                eventname = 'on_mouse_down'
                if event.type == pygame.MOUSEBUTTONUP:
                    eventname = 'on_mouse_up'
                self.dispatch(eventname, x, y, btn, self.modifiers)

            # keyboard action
            elif event.type in (pygame.KEYDOWN, pygame.KEYUP):
                self._pygame_update_modifiers(event.mod)
                # atm, don't handle keyup
                if event.type == pygame.KEYUP:
                    self.dispatch('on_key_up', event.key,
                        event.scancode)
                    continue

                # don't dispatch more key if down event is accepted
                if self.dispatch('on_key_down', event.key,
                                       event.scancode, event.unicode):
                    continue
                self.dispatch('on_keyboard', event.key,
                                    event.scancode, event.unicode)

            # video resize
            elif event.type == pygame.VIDEORESIZE:
                pass

            # ignored event
            elif event.type in (pygame.ACTIVEEVENT, pygame.VIDEOEXPOSE):
                pass

            # unhandled event !
            else:
                Logger.debug('WinPygame: Unhandled event %s' % str(event))
Exemplo n.º 2
0
    def test_scrollbar_both_margin(self):
        EventLoop.ensure_window()
        win = EventLoop.window
        grid = TestGrid()
        scroll = TestScrollbarBothMargin()
        margin = scroll.bar_margin
        scroll.add_widget(grid)
        win.add_widget(scroll)

        # get widgets ready
        EventLoop.idle()

        left, right = scroll.to_window(scroll.x, scroll.right)
        bottom, top = scroll.to_window(scroll.y, scroll.top)

        # touch in the half of the bar
        m = margin + scroll.bar_width / 2.0
        points = [
            [left, bottom + m, right, bottom + m, 'bottom', 'right', False],
            [left, top - m, right, top - m, 'top', 'right', False],
            [right - m, top, right - m, bottom, 'bottom', 'right', False],
            [left + m, top, left + m, bottom, 'bottom', 'left', False],
            [left, bottom, right, bottom, 'bottom', 'right', True],
            [left, top, right, top, 'top', 'right', True],
            [right, top, right, bottom, 'bottom', 'right', True],
            [left, top, left, bottom, 'bottom', 'left', True]
        ]
        self.process_points(scroll, points)
        self.render(scroll)
Exemplo n.º 3
0
def PopupOk(text, title='', btn_text='Continue', input=None, callback=None):
    btnclose = Button(text=btn_text, size_hint_y=None, height='50sp')
    content = BoxLayout(orientation='vertical')
    p = Popup(title=title, content=content, size=('300dp', '300dp'),
                size_hint=(None, None), pos_hint={'top':.95})
    content.add_widget(Label(text=text))
    if input is not None:
        assert callback is not None
        ti = TextInput(height='50sp', font_size='30sp', input_type=input,
                        multiline=False, size_hint_y = None, focus=True)
        content.add_widget(ti)
        def _callback(*args):
            try:
                ti.hide_keyboard()
            except AttributeError:
                # On a real computer, not the phone
                pass
            if ti.text == '':
                callback(None)
            else:
                callback(ti.text)
        p.bind(on_dismiss=_callback)
        p.is_visable = True

    content.add_widget(btnclose)

    btnclose.bind(on_release=p.dismiss)
    p.open()
    if input is not None:
        while not p.is_visable:
            EventLoop.idle()
        return ti.text
Exemplo n.º 4
0
 def inner(*args):
     #Here is hould loop on the template to apply them on values
     from kivy.base import EventLoop
     EventLoop.idle()
     pim = tmpl.toPILImage(for_print = True).rotate(90)
     pm.setImage(pim)
     self.stack.add_widget(pm)
Exemplo n.º 5
0
 def inner(*args):
     #Here is hould loop on the template to apply them on values
     from kivy.base import EventLoop
     EventLoop.idle()
     cim = tmpl.toImage()
     cim.texture.flip_vertical()
     self.ids['img'].texture = cim.texture
Exemplo n.º 6
0
 def __init__(self,parent,**kwargs):
     from kivy.base import EventLoop
     self.result=None
     dlg = MessageBox(parent,**kwargs)
     while (dlg) and (self.result is None):
             EventLoop.idle()
     return self.result
Exemplo n.º 7
0
    def advance_real_time(self, secs=.1):
        start = self._current_time
        while self._current_time < start + secs:
            EventLoop.idle()
            sleep(1 / self._fps)
            self._current_time += 1 / self._fps

        EventLoop.idle()
Exemplo n.º 8
0
    def add_item(self, qt, verso):
            from os.path import relpath
            stack = App.get_running_app().root.ids['deck'].ids['stack']
            ##########################################################
            qt = int(qt)
            if self.is_all_folder:
                #print self, self.source, self.name, self.is_all_folder
                #It is a folder, add all the imge from folder
                for name in [x for x in os.listdir(self.is_all_folder) if x.endswith(FILE_FILTER)]:
                ##for fiv in self.parent.children:
                    ##if fiv.is_all_folder: continue
                    if name.endswith(('.csv','.xlsx')):
                        continue
                    box = StackPart()
                    #box.name = fiv.name
                    box.name = name
                    box.source = os.path.join(self.is_all_folder, name)
                    box.qt = qt
                    box.verso = verso
                    if name.endswith('.kv'):
                        if self.is_all_folder.startswith(gamepath):
                            fold = relpath(self.is_all_folder, gamepath)
                        else:
                            fold = self.is_all_folder
                        box.template = "@%s"%os.path.join(fold, name)
                        box.realise()
                    stack.add_widget(box)
                    from kivy.base import EventLoop
                    EventLoop.idle()
            elif self.name.endswith('.csv'):
                App.get_running_app().root.ids.deck.load_file_csv(self.name)
            elif self.name.endswith('.xlsx'):
                App.get_running_app().root.ids.deck.load_file(self.name)
            elif self.name.endswith('.bgp'):
                self.extract_package()
            elif self.name.endswith('.py'):
                print 'should be executing', self.name, self.source, self.is_all_folder
                from imp import load_source
                Logger.info('Executing PYScript file %s'%self.name)
                m = self.name
                load_source(m[:-3],m)


            else:
                box = StackPart()
                box.name = self.name
                box.source = self.source
                box.qt = qt
                box.verso = verso
                stack.add_widget(box)
                if self.name.endswith('.kv'):
                    box.tmplWidget = self.tmplWidget
                    if self.name.startswith(gamepath):
                        fold = relpath(self.name, gamepath)
                    else:
                        fold = self.name
                    box.template = "@%s"%fold
                    box.realise()
Exemplo n.º 9
0
 def advance_frames(self, count):
     """
     Borrowed from Kivy 1.10.0+ /kivy/tests/common.py
     GraphicUnitTest.advance_frames()
     Makes it possible to to wait for UI to process, refs #110.
     """
     from kivy.base import EventLoop
     for i in range(count):
         EventLoop.idle()
Exemplo n.º 10
0
 def __init__(self, raw_x, raw_y):
     win = EventLoop.window
     super().__init__("unittest", 1, {
         "x": raw_x / float(win.width),
         "y": raw_y / float(win.height),
     })
     # press & release
     EventLoop.post_dispatch_input("begin", self)
     EventLoop.post_dispatch_input("end", self)
     EventLoop.idle()
Exemplo n.º 11
0
def idle_until(condition, timeout=None, msg="Timed out"):
    if timeout is None:
        while not condition():
            EventLoop.idle()
        return
    for _ in range(timeout):
        if condition():
            return
        EventLoop.idle()
    raise TimeoutError(msg)
Exemplo n.º 12
0
    def update(self, value):
        self.value = value
        if 0.0 < value < 100.0:
            self.opacity = 1.0
        else:
            self.opacity = 0.0

        if time.time() - self.last_update > self.frame_time:
            EventLoop.idle()
            self.last_update = time.time()
Exemplo n.º 13
0
    def advance_frames(self, count):
        '''Render the new frames and:

        * tick the Clock
        * dispatch input from all registered providers
        * flush all the canvas operations
        * redraw Window canvas if necessary
        '''
        from kivy.base import EventLoop
        for i in range(count):
            EventLoop.idle()
Exemplo n.º 14
0
Arquivo: common.py Projeto: kivy/kivy
    def advance_frames(self, count):
        '''Render the new frames and:

        * tick the Clock
        * dispatch input from all registered providers
        * flush all the canvas operations
        * redraw Window canvas if necessary
        '''
        from kivy.base import EventLoop
        for i in range(count):
            EventLoop.idle()
Exemplo n.º 15
0
 def alert(self, text="", status_color=(0, 0, 0, 1), keep = False):
     button = self.root.ids.message
     bar = self.root.ids.message_bar
     bar.background_color = status_color
     button.text = str(text)
     from kivy.base import EventLoop
     EventLoop.idle()
     if not keep:
         from kivy.clock import Clock
         def cb(*args):
             self.alert(keep=True)
         Clock.schedule_once(cb, 2)
Exemplo n.º 16
0
    def __init__(self, raw_x, raw_y):
        win = EventLoop.window

        super(UTMotionEvent, self).__init__(
            "unittest", 1, {
                "x": raw_x / float(win.width),
                "y": raw_y / float(win.height),
            }
        )

        # press & release
        EventLoop.post_dispatch_input("begin", self)
        EventLoop.post_dispatch_input("end", self)
        EventLoop.idle()
Exemplo n.º 17
0
    def alert(self, text="", status_color=(0, 0, 0, 1), keep=False):
        button = self.root.ids.message
        bar = self.root.ids.message_bar
        bar.background_color = status_color
        button.text = str(text)
        from kivy.base import EventLoop
        EventLoop.idle()
        if not keep:
            from kivy.clock import Clock

            def cb(*args):
                self.alert(keep=True)

            Clock.schedule_once(cb, 2)
Exemplo n.º 18
0
    def test_layout_grid():
        spots_wide = 3
        spots_tall = 3
        graph = nx.grid_2d_graph(spots_wide, spots_tall)
        char = Facade(graph)
        app = ELiDEApp()
        spotlayout = FinalLayout()
        arrowlayout = FinalLayout()
        board = GraphBoard(app=app,
                           character=char,
                           spotlayout=spotlayout,
                           arrowlayout=arrowlayout)
        spotlayout.pos = board.pos
        board.bind(pos=spotlayout.setter('pos'))
        spotlayout.size = board.size
        board.bind(size=spotlayout.setter('size'))
        board.add_widget(spotlayout)
        arrowlayout.pos = board.pos
        board.bind(pos=arrowlayout.setter('pos'))
        arrowlayout.size = board.size
        board.bind(size=arrowlayout.setter('size'))
        board.add_widget(arrowlayout)
        board.update()
        boardview = GraphBoardView(board=board)
        EventLoop.ensure_window()
        win = EventLoop.window
        win.add_widget(boardview)

        def all_spots_placed():
            for x in range(spots_wide):
                for y in range(spots_tall):
                    if (x, y) not in board.spot:
                        return False
            return True

        while not all_spots_placed():
            EventLoop.idle()
        # Don't get too picky about the exact proportions of the grid; just make sure the
        # spots are positioned logically with respect to one another
        for name, spot in board.spot.items():
            x, y = name
            if x > 0:
                assert spot.x > board.spot[x - 1, y].x
            if y > 0:
                assert spot.y > board.spot[x, y - 1].y
            if x < spots_wide - 1:
                assert spot.x < board.spot[x + 1, y].x
            if y < spots_tall - 1:
                assert spot.y < board.spot[x, y + 1].y
Exemplo n.º 19
0
    def test_scrollbar_vertical(self):
        EventLoop.ensure_window()
        win = EventLoop.window
        grid = _TestGrid()
        scroll = _TestScrollbarVertical()
        scroll.add_widget(grid)
        win.add_widget(scroll)

        # get widgets ready
        EventLoop.idle()

        left, right = scroll.to_window(scroll.x, scroll.right)
        bottom, top = scroll.to_window(scroll.y, scroll.top)

        points = [[right, top, right, bottom, 'bottom', 'right', False],
                  [left, top, left, bottom, 'bottom', 'left', False]]
        self.process_points(scroll, points)
        self.render(scroll)
Exemplo n.º 20
0
    def test_scrollbar_vertical(self):
        EventLoop.ensure_window()
        win = EventLoop.window
        grid = TestGrid()
        scroll = TestScrollbarVertical()
        scroll.add_widget(grid)
        win.add_widget(scroll)

        # get widgets ready
        EventLoop.idle()

        left, right = scroll.to_window(scroll.x, scroll.right)
        bottom, top = scroll.to_window(scroll.y, scroll.top)

        points = [
            [right, top, right, bottom, 'bottom', 'right', False],
            [left, top, left, bottom, 'bottom', 'left', False]
        ]
        self.process_points(scroll, points)
        self.render(scroll)
Exemplo n.º 21
0
def rpc_drag(selector, target, duration):
    from kivy.base import EventLoop
    w1 = selectFirst(selector)
    w2 = selectFirst(target)
    duration = float(duration)
    if w1 and w2:
        from kivy.core.window import Window
        cx1, cy1 = w1.to_window(w1.center_x, w1.center_y)
        sx1 = cx1 / float(Window.width)
        sy1 = cy1 / float(Window.height)

        me = TeleniumMotionEvent("telenium",
                                 id=next(nextid),
                                 args=[sx1, sy1])

        telenium_input.events.append(("begin", me))
        if not duration:
            telenium_input.events.append(("end", me))

        else:
            d = 0
            while d < duration:
                t = time()
                EventLoop.idle()
                dt = time() - t
                # need to compute that ever frame, it could have moved
                cx2, cy2 = w2.to_window(w2.center_x, w2.center_y)
                sx2 = cx2 / float(Window.width)
                sy2 = cy2 / float(Window.height)

                dsx = dt * (sx2 - me.sx) / (duration - d)
                dsy = dt * (sy2 - me.sy) / (duration - d)

                me.sx += dsx
                me.sy += dsy

                telenium_input.events.append(("update", me))
                d += dt

        telenium_input.events.append(("end", me))
        return True
Exemplo n.º 22
0
    def _event_filter(self, action, *largs):
        from kivy.app import App
        if action == 'app_terminating':
            EventLoop.quit = True

        elif action == 'app_lowmemory':
            self.dispatch('on_memorywarning')

        elif action == 'app_willenterbackground':
            from kivy.base import stopTouchApp
            app = App.get_running_app()
            if not app:
                Logger.info('WindowSDL: No running App found, exit.')
                stopTouchApp()
                return 0

            if not app.dispatch('on_pause'):
                Logger.info(
                    'WindowSDL: App doesn\'t support pause mode, stop.')
                stopTouchApp()
                return 0

            self._pause_loop = True

        elif action == 'app_didenterforeground':
            # on iOS, the did enter foreground is launched at the start
            # of the application. in our case, we want it only when the app
            # is resumed
            if self._pause_loop:
                self._pause_loop = False
                app = App.get_running_app()
                app.dispatch('on_resume')

        elif action == 'windowresized':
            self._size = largs
            self._win.resize_window(*self._size)
            # Force kivy to render the frame now, so that the canvas is drawn.
            EventLoop.idle()

        return 0
Exemplo n.º 23
0
    def _event_filter(self, action, *largs):
        from kivy.app import App
        if action == 'app_terminating':
            EventLoop.quit = True

        elif action == 'app_lowmemory':
            self.dispatch('on_memorywarning')

        elif action == 'app_willenterbackground':
            from kivy.base import stopTouchApp
            app = App.get_running_app()
            if not app:
                Logger.info('WindowSDL: No running App found, exit.')
                stopTouchApp()
                return 0

            if not app.dispatch('on_pause'):
                Logger.info(
                    'WindowSDL: App doesn\'t support pause mode, stop.')
                stopTouchApp()
                return 0

            self._pause_loop = True

        elif action == 'app_didenterforeground':
            # on iOS, the did enter foreground is launched at the start
            # of the application. in our case, we want it only when the app
            # is resumed
            if self._pause_loop:
                self._pause_loop = False
                app = App.get_running_app()
                app.dispatch('on_resume')

        elif action == 'windowresized':
            self._size = largs
            self._win.resize_window(*self._size)
            # Force kivy to render the frame now, so that the canvas is drawn.
            EventLoop.idle()

        return 0
Exemplo n.º 24
0
 def linearize(self,progressbar = None):
     #transform all stack with qt>1 to as many stack with qt 1
     cs = self.ids.stack.children[:]
     cs.reverse()
     dst = list()
     if progressbar:
         from kivy.base import EventLoop
         progressbar.value = 0
         progressbar.max = len(cs) * 2
     for c in cs:
         if progressbar:
             progressbar.value+=1
             EventLoop.idle()
         for _ in range(c.qt):
             d = c.Copy()
             d.qt = 1
             dst.append(d)
     self.ids.stack.clear_widgets()
     for d in dst:
         if progressbar:
             progressbar.value += 1
             EventLoop.idle()
         self.ids.stack.add_widget(d)
         d.realise(use_cache=True)
Exemplo n.º 25
0
 def linearize(self, progressbar=None):
     #transform all stack with qt>1 to as many stack with qt 1
     cs = self.ids.stack.children[:]
     cs.reverse()
     dst = list()
     if progressbar:
         from kivy.base import EventLoop
         progressbar.value = 0
         progressbar.max = len(cs) * 2
     for c in cs:
         if progressbar:
             progressbar.value += 1
             EventLoop.idle()
         for _ in range(c.qt):
             d = c.Copy()
             d.qt = 1
             dst.append(d)
     self.ids.stack.clear_widgets()
     for d in dst:
         if progressbar:
             progressbar.value += 1
             EventLoop.idle()
         self.ids.stack.add_widget(d)
         d.realise(use_cache=True)
Exemplo n.º 26
0
    def _start_app_as_slave(self):
        # from app::run
        if not self.mc.built:
            self.mc.load_config()
            self.mc.load_kv(filename=self.mc.kv_file)
            root = self.mc.build()
            if root:
                self.mc.root = root
        if self.mc.root:
            if not isinstance(self.mc.root, KivyWidget):
                Logger.critical(
                    'App.root must be an _instance_ of Kivy Widget')
                raise Exception('Invalid instance in App.root')
            from kivy.core.window import Window
            Window.add_widget(self.mc.root)

        # Check if the window is already created
        from kivy.base import EventLoop
        window = EventLoop.window
        if window:
            self.mc._app_window = window
            window.set_title(self.mc.get_application_name())
            icon = self.mc.get_application_icon()
            if icon:
                window.set_icon(icon)
            self.mc._install_settings_keys(window)
        else:
            Logger.critical("Application: No window is created."
                            " Terminating application run.")
            return

        self.mc.dispatch('on_start')
        runTouchApp(slave=True)  # change is here

        while not self.mc.is_init_done.is_set():
            EventLoop.idle()
Exemplo n.º 27
0
    def test_scrollbar_vertical_margin(self):
        EventLoop.ensure_window()
        win = EventLoop.window
        grid = _TestGrid()
        scroll = _TestScrollbarVerticalMargin()
        margin = scroll.bar_margin
        scroll.add_widget(grid)
        win.add_widget(scroll)

        # get widgets ready
        EventLoop.idle()

        left, right = scroll.to_window(scroll.x, scroll.right)
        bottom, top = scroll.to_window(scroll.y, scroll.top)

        # touch in the half of the bar
        m = margin + scroll.bar_width / 2.0
        points = [[
            right - m, top, right - m, bottom, 'bottom', 'right', False
        ], [left + m, top, left + m, bottom, 'bottom', 'left', False],
                  [right, top, right, bottom, 'bottom', 'right', True],
                  [left, top, left, bottom, 'bottom', 'left', True]]
        self.process_points(scroll, points)
        self.render(scroll)
Exemplo n.º 28
0
    def scanAllEcus(self):
        SEFname = mod_globals.user_data_dir + '/savedEcus.p'
        if mod_globals.opt_can2:
            SEFname = mod_globals.user_data_dir + '/savedEcus2.p'
        if mod_globals.opt_demo and not os.path.isfile(SEFname):
            SEFname = './savedEcus.p'
        if os.path.isfile(SEFname) and not mod_globals.opt_scan:
            self.detectedEcus = pickle.load(open(SEFname, 'rb'))
            if len(self.detectedEcus
                   ) > 0 and 'idTx' not in self.detectedEcus[0].keys():
                self.allecus = OrderedDict()
                for i in self.detectedEcus:
                    self.allecus[i['ecuname']] = i

                self.read_Uces_file()
                self.detectedEcus = []
                for i in self.allecus.keys():
                    self.detectedEcus.append(self.allecus[i])

                self.detectedEcus = sorted(self.detectedEcus,
                                           key=lambda k: int(k['idf']))
                if len(self.detectedEcus):
                    pickle.dump(self.detectedEcus, open(SEFname, 'wb'))
            return None
        mod_globals.opt_scan = True
        mod_globals.state_scan = True
        lbltxt = Label(text='Init', font_size=20)
        popup_scan = Popup(title='Scanning CAN bus',
                           content=lbltxt,
                           size=(400, 400),
                           size_hint=(None, None))
        base.runTouchApp(slave=True)
        popup_scan.open()
        EventLoop.idle()
        self.reqres = []
        self.errres = []
        i = 0
        lbltxt.text = 'Scanning:' + str(i) + '/' + str(len(
            self.allecus)) + ' Detected: ' + str(len(self.detectedEcus))
        EventLoop.idle()
        canH = '6'
        canL = '14'
        if mod_globals.opt_can2:
            canH = '13'
            canL = '12'
        self.elm.init_can()
        for ecu, row in sorted(self.allecus.iteritems(),
                               key=lambda (x, y): y['idf'] + y['protocol']):
            if self.allecus[ecu]['pin'] == 'can' and self.allecus[ecu][
                    'pin1'] == canH and self.allecus[ecu]['pin2'] == canL:
                i = i + 1
                lbltxt.text = 'Scanning:' + str(i) + '/' + str(
                    len(self.allecus)) + ' Detected: ' + str(
                        len(self.detectedEcus))
                EventLoop.idle()
                self.elm.set_can_addr(self.allecus[ecu]['dst'],
                                      self.allecus[ecu])
                self.scan_can(self.allecus[ecu])

        self.elm.close_protocol()
        if not mod_globals.opt_can2:
            popup_scan.title = 'Scanning ISO bus'
            self.elm.init_iso()
            for ecu, row in sorted(self.allecus.iteritems(),
                                   key=lambda
                                   (x, y): y['idf'] + y['protocol']):
                if self.allecus[ecu]['pin'] == 'iso' and self.allecus[ecu][
                        'pin1'] == '7' and self.allecus[ecu]['pin2'] == '15':
                    i = i + 1
                    lbltxt.text = 'Scanning:' + str(i) + '/' + str(
                        len(self.allecus)) + ' Detected: ' + str(
                            len(self.detectedEcus))
                    EventLoop.idle()
                    self.elm.set_iso_addr(self.allecus[ecu]['dst'],
                                          self.allecus[ecu])
                    self.scan_iso(self.allecus[ecu])

        lbltxt.text = 'Scanning:' + str(i) + '/' + str(len(
            self.allecus)) + ' Detected: ' + str(len(self.detectedEcus))
        EventLoop.idle()
        mod_globals.state_scan = False
        self.detectedEcus = sorted(self.detectedEcus,
                                   key=lambda k: int(k['idf']))
        if len(self.detectedEcus):
            pickle.dump(self.detectedEcus, open(SEFname, 'wb'))
        EventLoop.window.remove_widget(popup_scan)
        popup_scan.dismiss()
        base.stopTouchApp()
        EventLoop.window.canvas.clear()
        del popup_scan
Exemplo n.º 29
0
    def _mainloop(self):
        EventLoop.idle()

        for event in pygame.event.get():

            # kill application (SIG_TERM)
            if event.type == pygame.QUIT:
                if self.dispatch('on_request_close'):
                    continue
                EventLoop.quit = True
                self.close()

            # mouse move
            elif event.type == pygame.MOUSEMOTION:
                x, y = event.pos
                self.mouse_pos = x, self.system_size[1] - y
                # don't dispatch motion if no button are pressed
                if event.buttons == (0, 0, 0):
                    continue
                self._mouse_x = x
                self._mouse_y = y
                self._mouse_meta = self.modifiers
                self.dispatch('on_mouse_move', x, y, self.modifiers)

            # mouse action
            elif event.type in (pygame.MOUSEBUTTONDOWN,
                                pygame.MOUSEBUTTONUP):
                self._pygame_update_modifiers()
                x, y = event.pos
                btn = 'left'
                if event.button == 3:
                    btn = 'right'
                elif event.button == 2:
                    btn = 'middle'
                elif event.button == 4:
                    btn = 'scrolldown'
                elif event.button == 5:
                    btn = 'scrollup'
                elif event.button == 6:
                    btn = 'scrollright'
                elif event.button == 7:
                    btn = 'scrollleft'
                eventname = 'on_mouse_down'
                if event.type == pygame.MOUSEBUTTONUP:
                    eventname = 'on_mouse_up'
                self._mouse_x = x
                self._mouse_y = y
                self._mouse_meta = self.modifiers
                self._mouse_btn = btn
                self._mouse_down = eventname == 'on_mouse_down'
                self.dispatch(eventname, x, y, btn, self.modifiers)

            # keyboard action
            elif event.type in (pygame.KEYDOWN, pygame.KEYUP):
                self._pygame_update_modifiers(event.mod)
                # atm, don't handle keyup
                if event.type == pygame.KEYUP:
                    self.dispatch('on_key_up', event.key,
                                  event.scancode)
                    continue

                # don't dispatch more key if down event is accepted
                if self.dispatch('on_key_down', event.key,
                                 event.scancode, event.unicode,
                                 self.modifiers):
                    continue
                self.dispatch('on_keyboard', event.key,
                              event.scancode, event.unicode,
                              self.modifiers)

            # video resize
            elif event.type == pygame.VIDEORESIZE:
                self._size = event.size
                self.update_viewport()

            elif event.type == pygame.VIDEOEXPOSE:
                self.canvas.ask_update()

            # ignored event
            elif event.type == pygame.ACTIVEEVENT:
                pass

            # drop file (pygame patch needed)
            elif event.type == pygame.USEREVENT and \
                    hasattr(pygame, 'USEREVENT_DROPFILE') and \
                    event.code == pygame.USEREVENT_DROPFILE:
                self.dispatch('on_dropfile', event.filename)

            '''
Exemplo n.º 30
0
    def _mainloop(self):
        EventLoop.idle()

        while True:
            event = sdl.poll()
            if event is False:
                break
            if event is None:
                continue

            action, args = event[0], event[1:]
            if action == 'quit':
                EventLoop.quit = True
                self.close()
                break

            elif action in ('fingermotion', 'fingerdown', 'fingerup'):
                # for finger, pass the raw event to SDL motion event provider
                SDLMotionEventProvider.q.appendleft(event)

            if action == 'mousemotion':
                x, y = args
                self.dispatch('on_mouse_move', x, y, self.modifiers)

            elif action in ('mousebuttondown', 'mousebuttonup'):
                x, y, button = args
                btn = 'left'
                if button == 3:
                    btn = 'right'
                elif button == 2:
                    btn = 'middle'
                eventname = 'on_mouse_down'
                if action == 'mousebuttonup':
                    eventname = 'on_mouse_up'
                self.dispatch(eventname, x, y, btn, self.modifiers)

            # video resize
            elif action == 'windowresized':
                self._size = args
                # don't use trigger here, we want to delay the resize event
                cb = self._do_resize
                Clock.unschedule(cb)
                Clock.schedule_once(cb, .1)

            elif action == 'windowresized':
                self.canvas.ask_update()

            elif action == 'windowminimized':
                self.do_pause()

            elif action == 'windowrestored':
                pass

            elif action in ('keydown', 'keyup'):
                mod, key, scancode, str = args

                # XXX ios keyboard suck, when backspace is hit, the delete
                # keycode is sent. fix it.
                if key == 127:
                    key = 8

                self._pygame_update_modifiers(mod)
                if action == 'keyup':
                    self.dispatch('on_key_up', key, scancode)
                    continue

                # don't dispatch more key if down event is accepted
                if self.dispatch('on_key_down', key,
                                 scancode, str,
                                 self.modifiers):
                    continue
                self.dispatch('on_keyboard', key,
                              scancode, str,
                              self.modifiers)

            elif action == 'textinput':
                key = args[0][0]
                # XXX on IOS, keydown/up don't send unicode anymore.
                # With latest sdl, the text is sent over textinput
                # Right now, redo keydown/up, but we need to seperate both call
                # too. (and adapt on_key_* API.)
                self.dispatch('on_key_down', key, None, args[0],
                              self.modifiers)
                self.dispatch('on_keyboard', None, None, args[0],
                              self.modifiers)
                self.dispatch('on_key_up', key, None, args[0],
                              self.modifiers)
Exemplo n.º 31
0
    def _mainloop(self):
        EventLoop.idle()

        # for android/iOS, we don't want to have any event nor executing our
        # main loop while the pause is going on. This loop wait any event (not
        # handled by the event filter), and remove them from the queue.
        # Nothing happen during the pause on iOS, except gyroscope value sent
        # over joystick. So it's safe.
        while self._pause_loop:
            self._win.wait_event()
            if not self._pause_loop:
                break
            self._win.poll()

        while True:
            event = self._win.poll()
            if event is False:
                break
            if event is None:
                continue

            action, args = event[0], event[1:]
            if action == 'quit':
                if self.dispatch('on_request_close'):
                    continue
                EventLoop.quit = True
                self.close()
                break

            elif action in ('fingermotion', 'fingerdown', 'fingerup'):
                # for finger, pass the raw event to SDL motion event provider
                # XXX this is problematic. On OSX, it generates touches with 0,
                # 0 coordinates, at the same times as mouse. But it works.
                # We have a conflict of using either the mouse or the finger.
                # Right now, we have no mechanism that we could use to know
                # which is the preferred one for the application.
                if platform in ('ios', 'android'):
                    SDL2MotionEventProvider.q.appendleft(event)
                pass

            elif action == 'mousemotion':
                x, y = args
                x, y = self._fix_mouse_pos(x, y)
                self._mouse_x = x
                self._mouse_y = y
                # don't dispatch motion if no button are pressed
                if len(self._mouse_buttons_down) == 0:
                    continue
                self._mouse_meta = self.modifiers
                self.dispatch('on_mouse_move', x, y, self.modifiers)

            elif action in ('mousebuttondown', 'mousebuttonup'):
                x, y, button = args
                x, y = self._fix_mouse_pos(x, y)
                btn = 'left'
                if button == 3:
                    btn = 'right'
                elif button == 2:
                    btn = 'middle'
                eventname = 'on_mouse_down'
                self._mouse_buttons_down.add(button)
                if action == 'mousebuttonup':
                    eventname = 'on_mouse_up'
                    self._mouse_buttons_down.remove(button)
                self._mouse_x = x
                self._mouse_y = y
                self.dispatch(eventname, x, y, btn, self.modifiers)
            elif action.startswith('mousewheel'):
                self._update_modifiers()
                x, y, button = args
                btn = 'scrolldown'
                if action.endswith('up'):
                    btn = 'scrollup'
                elif action.endswith('right'):
                    btn = 'scrollright'
                elif action.endswith('left'):
                    btn = 'scrollleft'

                self._mouse_meta = self.modifiers
                self._mouse_btn = btn
                #times = x if y == 0 else y
                #times = min(abs(times), 100)
                #for k in range(times):
                self._mouse_down = True
                self.dispatch('on_mouse_down', self._mouse_x, self._mouse_y,
                              btn, self.modifiers)
                self._mouse_down = False
                self.dispatch('on_mouse_up', self._mouse_x, self._mouse_y, btn,
                              self.modifiers)

            elif action == 'dropfile':
                dropfile = args
                self.dispatch('on_dropfile', dropfile[0])
            # video resize
            elif action == 'windowresized':
                self._size = self._win.window_size
                # don't use trigger here, we want to delay the resize event
                ev = self._do_resize_ev
                if ev is None:
                    ev = self._do_resize_ev = Clock.schedule_once(
                        self._do_resize, .1)
                else:
                    ev()

            elif action == 'windowresized':
                self.canvas.ask_update()

            elif action == 'windowrestored':
                self.dispatch('on_restore')
                self.canvas.ask_update()

            elif action == 'windowexposed':
                self.canvas.ask_update()

            elif action == 'windowminimized':
                self.dispatch('on_minimize')
                if Config.getboolean('kivy', 'pause_on_minimize'):
                    self.do_pause()

            elif action == 'windowmaximized':
                self.dispatch('on_maximize')

            elif action == 'windowhidden':
                self.dispatch('on_hide')

            elif action == 'windowshown':
                self.dispatch('on_show')

            elif action == 'windowfocusgained':
                self._focus = True

            elif action == 'windowfocuslost':
                self._focus = False

            elif action == 'windowenter':
                self.dispatch('on_cursor_enter')

            elif action == 'windowleave':
                self.dispatch('on_cursor_leave')

            elif action == 'joyaxismotion':
                stickid, axisid, value = args
                self.dispatch('on_joy_axis', stickid, axisid, value)
            elif action == 'joyhatmotion':
                stickid, hatid, value = args
                self.dispatch('on_joy_hat', stickid, hatid, value)
            elif action == 'joyballmotion':
                stickid, ballid, xrel, yrel = args
                self.dispatch('on_joy_ball', stickid, ballid, xrel, yrel)
            elif action == 'joybuttondown':
                stickid, buttonid = args
                self.dispatch('on_joy_button_down', stickid, buttonid)
            elif action == 'joybuttonup':
                stickid, buttonid = args
                self.dispatch('on_joy_button_up', stickid, buttonid)

            elif action in ('keydown', 'keyup'):
                mod, key, scancode, kstr = args

                try:
                    key = self.key_map[key]
                except KeyError:
                    pass

                if action == 'keydown':
                    self._update_modifiers(mod, key)
                else:
                    self._update_modifiers(mod)  # ignore the key, it
                    # has been released

                # if mod in self._meta_keys:
                if (key not in self._modifiers
                        and key not in self.command_keys.keys()):
                    try:
                        kstr = unichr(key)
                    except ValueError:
                        pass
                #if 'shift' in self._modifiers and key\
                #        not in self.command_keys.keys():
                #    return

                if action == 'keyup':
                    self.dispatch('on_key_up', key, scancode)
                    continue

                # don't dispatch more key if down event is accepted
                if self.dispatch('on_key_down', key, scancode, kstr,
                                 self.modifiers):
                    continue
                self.dispatch('on_keyboard', key, scancode, kstr,
                              self.modifiers)

            elif action == 'textinput':
                text = args[0]
                self.dispatch('on_textinput', text)

            # unhandled event !
            else:
                Logger.trace('WindowSDL: Unhandled event %s' % str(event))
Exemplo n.º 32
0
    def test_slider_move(self):
        EventLoop.ensure_window()
        win = EventLoop.window
        layout = BoxLayout(orientation='vertical')

        s_handle = _TestSliderHandle()
        s_all = _TestSliderAll()
        layout.add_widget(s_handle)
        layout.add_widget(s_all)
        win.add_widget(layout)

        # get widgets ready
        EventLoop.idle()

        cur1 = s_handle.children[0]
        cur2 = s_all.children[0]

        h1 = cur1.to_window(*cur1.center)[1]
        h2 = h1 - s_handle.cursor_height
        h3 = cur2.to_window(*cur2.center)[1]
        h4 = h3 - s_all.cursor_height

        w1 = cur1.to_window(*cur1.center)[0]
        w2 = cur2.to_window(*cur2.center)[0]
        wh = win.width / 2.0
        dt = 2

        # default pos, new pos, slider ID
        points = [
            [w1, h1, wh, h1, 'handle'],
            [w1, h2, wh, h2, 'handle'],
            [w2, h3, wh, h3, 'all'],
            [w2, h4, wh, h4, 'all'],
        ]

        for point in points:
            x, y, nx, ny, id = point

            # custom touch
            touch = UTMotionEvent("unittest", 1, {
                "x": x / float(win.width),
                "y": y / float(win.height),
            })

            # touch down
            EventLoop.post_dispatch_input("begin", touch)

            if id == 'handle':
                # touch on handle
                if x == w1 and y == h1:
                    self.assertAlmostEqual(s_handle.value, 0.0, delta=dt)
                # touch in widget area (ignored, previous value)
                elif x == w1 and y == h2:
                    self.assertAlmostEqual(s_handle.value, 50.0, delta=dt)
            elif id == 'all':
                # touch on handle:
                if x == w1 and y == h3:
                    self.assertAlmostEqual(s_all.value, 0.0, delta=dt)
                # touch in widget area
                elif x == w1 and y == h4:
                    self.assertAlmostEqual(s_all.value, 0.0, delta=dt)

            # move from default to new pos
            touch.move({
                "x": nx / float(win.width),
                "y": ny / float(win.height)
            })
            EventLoop.post_dispatch_input("update", touch)

            if id == 'handle':
                # move from handle to center
                if nx == wh and ny == h1:
                    self.assertAlmostEqual(s_handle.value, 50.0, delta=dt)
                # move to center (ignored, previous value)
                elif nx == wh and ny == h2:
                    self.assertAlmostEqual(s_handle.value, 50.0, delta=dt)
            elif id == 'all':
                # touch on handle:
                if nx == wh and ny == h3:
                    self.assertAlmostEqual(s_all.value, 50.0, delta=dt)
                # touch in widget area
                elif nx == wh and ny == h4:
                    self.assertAlmostEqual(s_all.value, 50.0, delta=dt)

            # touch up
            EventLoop.post_dispatch_input("end", touch)

        self.render(layout)
Exemplo n.º 33
0
    def _mainloop(self):
        EventLoop.idle()

        while True:
            event = self._win.poll()
            if event is False:
                break
            if event is None:
                continue

            action, args = event[0], event[1:]
            if action == 'quit':
                if self.dispatch('on_request_close'):
                    continue
                EventLoop.quit = True
                self.close()
                break

            elif action in ('fingermotion', 'fingerdown', 'fingerup'):
                # for finger, pass the raw event to SDL motion event provider
                # XXX this is problematic. On OSX, it generates touches with 0,
                # 0 coordinates, at the same times as mouse. But it works.
                # We have a conflict of using either the mouse or the finger.
                # Right now, we have no mechanism that we could use to know
                # which is the preferred one for the application.
                if platform == "ios":
                    SDL2MotionEventProvider.q.appendleft(event)
                pass

            elif action == 'mousemotion':
                x, y = args
                x, y = self._fix_mouse_pos(x, y)
                self._mouse_x = x
                self._mouse_y = y
                # don't dispatch motion if no button are pressed
                if len(self._mouse_buttons_down) == 0:
                    continue
                self._mouse_meta = self.modifiers
                self.dispatch('on_mouse_move', x, y, self.modifiers)

            elif action in ('mousebuttondown', 'mousebuttonup'):
                x, y, button = args
                x, y = self._fix_mouse_pos(x, y)
                btn = 'left'
                if button == 3:
                    btn = 'right'
                elif button == 2:
                    btn = 'middle'
                eventname = 'on_mouse_down'
                self._mouse_buttons_down.add(button)
                if action == 'mousebuttonup':
                    eventname = 'on_mouse_up'
                    self._mouse_buttons_down.remove(button)
                self._mouse_x = x
                self._mouse_y = y
                self.dispatch(eventname, x, y, btn, self.modifiers)
            elif action.startswith('mousewheel'):
                self._update_modifiers()
                x, y, button = args
                btn = 'scrolldown'
                if action.endswith('up'):
                    btn = 'scrollup'
                elif action.endswith('right'):
                    btn = 'scrollright'
                elif action.endswith('left'):
                    btn = 'scrollleft'

                self._mouse_meta = self.modifiers
                self._mouse_btn = btn
                #times = x if y == 0 else y
                #times = min(abs(times), 100)
                #for k in range(times):
                self._mouse_down = True
                self.dispatch('on_mouse_down',
                    self._mouse_x, self._mouse_y, btn, self.modifiers)
                self._mouse_down = False
                self.dispatch('on_mouse_up',
                    self._mouse_x, self._mouse_y, btn, self.modifiers)

            elif action == 'dropfile':
                dropfile = args
                self.dispatch('on_dropfile', dropfile[0])
            # video resize
            elif action == 'windowresized':
                self._size = self._win.window_size
                # don't use trigger here, we want to delay the resize event
                cb = self._do_resize
                Clock.unschedule(cb)
                Clock.schedule_once(cb, .1)

            elif action == 'windowresized':
                self.canvas.ask_update()

            elif action == 'windowrestored':
                self.canvas.ask_update()

            elif action == 'windowexposed':
                self.canvas.ask_update()

            elif action == 'windowminimized':
                if Config.getboolean('kivy', 'pause_on_minimize'):
                    self.do_pause()

            elif action == 'joyaxismotion':
                stickid, axisid, value = args
                self.dispatch('on_joy_axis', stickid, axisid, value)
            elif action == 'joyhatmotion':
                stickid, hatid, value = args
                self.dispatch('on_joy_hat', stickid, hatid, value)
            elif action == 'joyballmotion':
                stickid, ballid, xrel, yrel = args
                self.dispatch('on_joy_ball', stickid, ballid, xrel, yrel)
            elif action == 'joybuttondown':
                stickid, buttonid = args
                self.dispatch('on_joy_button_down', stickid, buttonid)
            elif action == 'joybuttonup':
                stickid, buttonid = args
                self.dispatch('on_joy_button_up', stickid, buttonid)

            elif action in ('keydown', 'keyup'):
                mod, key, scancode, kstr = args

                key_swap = {
                    SDLK_LEFT: 276, SDLK_RIGHT: 275, SDLK_UP: 273,
                    SDLK_DOWN: 274, SDLK_HOME: 278, SDLK_END: 279,
                    SDLK_PAGEDOWN: 281, SDLK_PAGEUP: 280, SDLK_SHIFTR: 303,
                    SDLK_SHIFTL: 304, SDLK_SUPER: 309, SDLK_LCTRL: 305,
                    SDLK_RCTRL: 306, SDLK_LALT: 308, SDLK_RALT: 307,
                    SDLK_CAPS: 301, SDLK_INSERT: 277, SDLK_F1: 282,
                    SDLK_F2: 283, SDLK_F3: 284, SDLK_F4: 285, SDLK_F5: 286,
                    SDLK_F6: 287, SDLK_F7: 288, SDLK_F8: 289, SDLK_F9: 290,
                    SDLK_F10: 291, SDLK_F11: 292, SDLK_F12: 293, SDLK_F13: 294,
                    SDLK_F14: 295, SDLK_F15: 296, SDLK_KEYPADNUM: 300,
                    SDLK_KP_DEVIDE: 267, SDLK_KP_MULTIPLY: 268,
                    SDLK_KP_MINUS: 269, SDLK_KP_PLUS: 270, SDLK_KP_ENTER: 271,
                    SDLK_KP_DOT: 266, SDLK_KP_0: 256, SDLK_KP_1: 257,
                    SDLK_KP_2: 258, SDLK_KP_3: 259, SDLK_KP_4: 260,
                    SDLK_KP_5: 261, SDLK_KP_6: 262, SDLK_KP_7: 263,
                    SDLK_KP_8: 264, SDLK_KP_9: 265}

                if platform == 'ios':
                    # XXX ios keyboard suck, when backspace is hit, the delete
                    # keycode is sent. fix it.
                    key_swap[127] = 8  # back

                try:
                    key = key_swap[key]
                except KeyError:
                    pass

                if action == 'keydown':
                    self._update_modifiers(mod, key)
                else:
                    self._update_modifiers(mod)  # ignore the key, it
                                                 # has been released

                # if mod in self._meta_keys:
                if (key not in self._modifiers and
                    key not in self.command_keys.keys()):
                    try:
                        kstr = unichr(key)
                    except ValueError:
                        pass
                #if 'shift' in self._modifiers and key\
                #        not in self.command_keys.keys():
                #    return

                if action == 'keyup':
                    self.dispatch('on_key_up', key, scancode)
                    continue

                # don't dispatch more key if down event is accepted
                if self.dispatch('on_key_down', key,
                                 scancode, kstr,
                                 self.modifiers):
                    continue
                self.dispatch('on_keyboard', key,
                              scancode, kstr,
                              self.modifiers)

            elif action == 'textinput':
                text = args[0]
                self.dispatch('on_textinput', text)
                # XXX on IOS, keydown/up don't send unicode anymore.
                # With latest sdl, the text is sent over textinput
                # Right now, redo keydown/up, but we need to seperate both call
                # too. (and adapt on_key_* API.)
                #self.dispatch()
                #self.dispatch('on_key_down', key, None, args[0],
                #              self.modifiers)
                #self.dispatch('on_keyboard', None, None, args[0],
                #              self.modifiers)
                #self.dispatch('on_key_up', key, None, args[0],
                #              self.modifiers)

            # unhandled event !
            else:
                Logger.trace('WindowSDL: Unhandled event %s' % str(event))
Exemplo n.º 34
0
 def _mainloop(self):
     EventLoop.idle()
Exemplo n.º 35
0
 def move_frames(self, t):
     for i in range(t):
         EventLoop.idle()
Exemplo n.º 36
0
            snds.append(_SOUNDFILES[d])
        else:
            return None

    if aPostfix:
        snds.append(aPostfix)

    return soundchain(snds, 1)


if __name__ == '__main__':
    from time import sleep
    from kivy.base import EventLoop

    running = True
    sound.start()

    s1 = makesoundchain(25, aPrefix='sys\\movement', aPostfix='sys\\percent')
    if s1:

        def cb(x):
            global running
            running = False

        s1.callback = cb
        s1.play()

        while running:
            EventLoop.idle()
            sleep(0.033)
Exemplo n.º 37
0
 def update_gui(self):
     if EventLoop.window and hasattr(EventLoop.window, '_mainloop'):
         EventLoop.window._mainloop()
     else:
         EventLoop.idle()
Exemplo n.º 38
0
    def test_smooth_scroll_end(self):
        EventLoop.ensure_window()
        win = EventLoop.window
        grid = TestGrid()
        scroll = ScrollView(smooth_scroll_end=10)

        assert scroll.smooth_scroll_end == 10
        scroll.add_widget(grid)

        # XXX this shouldn't be needed, but previous tests apparently
        # don't cleanup
        while win.children:
            win.remove_widget(win.children[0])

        win.add_widget(scroll)

        # get widgets ready
        EventLoop.idle()

        e = scroll.effect_y
        assert e.velocity == 0

        touch = UTMotionEvent("unittest", next(touch_id), {
            "x": scroll.center_x / float(win.width),
            "y": scroll.center_y / float(win.height),
        })

        touch.profile.append('button')
        touch.button = 'scrollup'

        EventLoop.post_dispatch_input("begin", touch)
        # EventLoop.post_dispatch_input("update", touch)
        assert e.velocity == 10 * scroll.scroll_wheel_distance
        EventLoop.idle()
        assert 0 < e.velocity < 10 * scroll.scroll_wheel_distance
        EventLoop.post_dispatch_input("end", touch)
        EventLoop.idle()
        assert 0 < e.velocity < 10 * scroll.scroll_wheel_distance

        # wait for velocity to die off
        while e.velocity:
            EventLoop.idle()

        touch = UTMotionEvent("unittest", next(touch_id), {
            "x": scroll.center_x / float(win.width),
            "y": scroll.center_y / float(win.height),
        })
        touch.profile.append('button')
        touch.button = 'scrolldown'

        EventLoop.post_dispatch_input("begin", touch)
        # EventLoop.post_dispatch_input("update", touch)
        assert e.velocity == -10 * scroll.scroll_wheel_distance
        EventLoop.idle()
        assert 0 > e.velocity > -10 * scroll.scroll_wheel_distance
        EventLoop.post_dispatch_input("end", touch)
        EventLoop.idle()
        assert 0 > e.velocity > -10 * scroll.scroll_wheel_distance
Exemplo n.º 39
0
def inputhook_myrmidon_kivy():
    """The kivy eventloop hook."""
    from kivy.base import EventLoop
    from kivy.utils import platform

    engine_window = Game.engine['window']
    if not engine_window or not engine_window.kivy_app:
        return 0

    kivy_app = engine_window.kivy_app
    if not kivy_app.built:
        from kivy.uix.widget import Widget
        from kivy.core.window import Window
        from kivy.base import runTouchApp

        for x in Game._module_list:
            x._module_setup(cls)

        kivy_app.load_config()
        kivy_app.load_kv(filename=kivy_app.kv_file)
        kivy_app.root = kivy_app.build()
        if not isinstance(kivy_app.root, Widget):
            raise Exception('Invalid instance in App.root')
        Window.add_widget(kivy_app.root)

        # Check if the window is already created
        window = EventLoop.window
        if window:
            kivy_app._app_window = window
            window.set_title(kivy_app.get_application_name())
            icon = kivy_app.get_application_icon()
            if icon:
                window.set_icon(icon)
            kivy_app._install_settings_keys(window)
        else:
            raise Exception("Application: No window is created."
                            " Terminating application run.")

        kivy_app.dispatch('on_start')
        runTouchApp(kivy_app.root, slave=True)

    # Tick forward the Myrmidon event loop one frame
    Game.app_loop_callback(0)

    # Tick forward kivy to reflect events and changes from Myrmidon.
    # This has been directly lifted from `kivy.core.window.window_sdl2`.
    EventLoop.idle()

    window = EventLoop.window
    event = window._win.poll()
    if event is False or event is None:
        return 0

    action, args = event[0], event[1:]
    if action == 'quit':
        EventLoop.quit = True
        window.close()
        return 0

    elif action in ('fingermotion', 'fingerdown', 'fingerup'):
        # for finger, pass the raw event to SDL motion event provider
        # XXX this is problematic. On OSX, it generates touches with 0,
        # 0 coordinates, at the same times as mouse. But it works.
        # We have a conflict of using either the mouse or the finger.
        # Right now, we have no mechanism that we could use to know
        # which is the preferred one for the application.
        if platform == "ios":
            SDL2MotionEventProvider.q.appendleft(event)
        pass

    elif action == 'mousemotion':
        x, y = args
        x, y = window._fix_mouse_pos(x, y)
        window._mouse_x = x
        window._mouse_y = y
        # don't dispatch motion if no button are pressed
        if len(window._mouse_buttons_down) == 0:
            return 0
        window._mouse_meta = window.modifiers
        window.dispatch('on_mouse_move', x, y, window.modifiers)

    elif action in ('mousebuttondown', 'mousebuttonup'):
        x, y, button = args
        x, y = window._fix_mouse_pos(x, y)
        btn = 'left'
        if button == 3:
            btn = 'right'
        elif button == 2:
            btn = 'middle'
        eventname = 'on_mouse_down'
        window._mouse_buttons_down.add(button)
        if action == 'mousebuttonup':
            eventname = 'on_mouse_up'
            window._mouse_buttons_down.remove(button)
        window._mouse_x = x
        window._mouse_y = y
        window.dispatch(eventname, x, y, btn, window.modifiers)
    elif action.startswith('mousewheel'):
        window._update_modifiers()
        x, y, button = args
        btn = 'scrolldown'
        if action.endswith('up'):
            btn = 'scrollup'
        elif action.endswith('right'):
            btn = 'scrollright'
        elif action.endswith('left'):
            btn = 'scrollleft'

        window._mouse_meta = window.modifiers
        window._mouse_btn = btn
        #times = x if y == 0 else y
        #times = min(abs(times), 100)
        #for k in range(times):
        window._mouse_down = True
        window.dispatch('on_mouse_down',
            window._mouse_x, window._mouse_y, btn, window.modifiers)
        window._mouse_down = False
        window.dispatch('on_mouse_up',
            window._mouse_x, window._mouse_y, btn, window.modifiers)

    elif action == 'dropfile':
        dropfile = args
        window.dispatch('on_dropfile', dropfile[0])
    # video resize
    elif action == 'windowresized':
        window._size = window._win.window_size
        # don't use trigger here, we want to delay the resize event
        cb = window._do_resize
        from kivy.clock import Clock
        Clock.unschedule(cb)
        Clock.schedule_once(cb, .1)

    elif action == 'windowresized':
        window.canvas.ask_update()

    elif action == 'windowrestored':
        window.canvas.ask_update()

    elif action == 'windowexposed':
        window.canvas.ask_update()

    elif action == 'windowminimized':
        if Config.getboolean('kivy', 'pause_on_minimize'):
            window.do_pause()

    elif action == 'joyaxismotion':
        stickid, axisid, value = args
        window.dispatch('on_joy_axis', stickid, axisid, value)
    elif action == 'joyhatmotion':
        stickid, hatid, value = args
        window.dispatch('on_joy_hat', stickid, hatid, value)
    elif action == 'joyballmotion':
        stickid, ballid, xrel, yrel = args
        window.dispatch('on_joy_ball', stickid, ballid, xrel, yrel)
    elif action == 'joybuttondown':
        stickid, buttonid = args
        window.dispatch('on_joy_button_down', stickid, buttonid)
    elif action == 'joybuttonup':
        stickid, buttonid = args
        window.dispatch('on_joy_button_up', stickid, buttonid)

    elif action in ('keydown', 'keyup'):
        mod, key, scancode, kstr = args

        from kivy.core.window import window_sdl2
        key_swap = {
            window_sdl2.SDLK_LEFT: 276, window_sdl2.SDLK_RIGHT: 275, window_sdl2.SDLK_UP: 273,
            window_sdl2.SDLK_DOWN: 274, window_sdl2.SDLK_HOME: 278, window_sdl2.SDLK_END: 279,
            window_sdl2.SDLK_PAGEDOWN: 281, window_sdl2.SDLK_PAGEUP: 280, window_sdl2.SDLK_SHIFTR: 303,
            window_sdl2.SDLK_SHIFTL: 304, window_sdl2.SDLK_SUPER: 309, window_sdl2.SDLK_LCTRL: 305,
            window_sdl2.SDLK_RCTRL: 306, window_sdl2.SDLK_LALT: 308, window_sdl2.SDLK_RALT: 307,
            window_sdl2.SDLK_CAPS: 301, window_sdl2.SDLK_INSERT: 277, window_sdl2.SDLK_F1: 282,
            window_sdl2.SDLK_F2: 283, window_sdl2.SDLK_F3: 284, window_sdl2.SDLK_F4: 285, window_sdl2.SDLK_F5: 286,
            window_sdl2.SDLK_F6: 287, window_sdl2.SDLK_F7: 288, window_sdl2.SDLK_F8: 289, window_sdl2.SDLK_F9: 290,
            window_sdl2.SDLK_F10: 291, window_sdl2.SDLK_F11: 292, window_sdl2.SDLK_F12: 293, window_sdl2.SDLK_F13: 294,
            window_sdl2.SDLK_F14: 295, window_sdl2.SDLK_F15: 296, window_sdl2.SDLK_KEYPADNUM: 300}

        if platform == 'ios':
            # XXX ios keyboard suck, when backspace is hit, the delete
            # keycode is sent. fix it.
            key_swap[127] = 8  # back

        try:
            key = key_swap[key]
        except KeyError:
            pass

        if action == 'keydown':
            window._update_modifiers(mod, key)
        else:
            window._update_modifiers(mod)  # ignore the key, it
                                         # has been released

        # if mod in window._meta_keys:
        if (key not in window._modifiers and
            key not in window.command_keys.keys()):
            try:
                kstr = chr(key)
            except ValueError:
                pass
        #if 'shift' in window._modifiers and key\
        #        not in window.command_keys.keys():
        #    return

        if action == 'keyup':
            window.dispatch('on_key_up', key, scancode)
            return 0

        # don't dispatch more key if down event is accepted
        if window.dispatch('on_key_down', key,
                         scancode, kstr,
                         window.modifiers):
            return 0
        window.dispatch('on_keyboard', key,
                      scancode, kstr,
                      window.modifiers)

    elif action == 'textinput':
        text = args[0]
        window.dispatch('on_textinput', text)
        # XXX on IOS, keydown/up don't send unicode anymore.
        # With latest sdl, the text is sent over textinput
        # Right now, redo keydown/up, but we need to seperate both call
        # too. (and adapt on_key_* API.)
        #window.dispatch()
        #window.dispatch('on_key_down', key, None, args[0],
        #              window.modifiers)
        #window.dispatch('on_keyboard', None, None, args[0],
        #              window.modifiers)
        #window.dispatch('on_key_up', key, None, args[0],
        #              window.modifiers)

    # unhandled event !
    else:
        from kivy.logger import Logger
        Logger.trace('WindowSDL: Unhandled event %s' % str(event))

    return 0
Exemplo n.º 40
0
    def _mainloop(self):
        EventLoop.idle()

        for event in pygame.event.get():

            # kill application (SIG_TERM)
            if event.type == pygame.QUIT:
                if self.dispatch("on_request_close"):
                    continue
                EventLoop.quit = True
                self.close()

            # mouse move
            elif event.type == pygame.MOUSEMOTION:
                x, y = event.pos
                self.mouse_pos = x, self.system_size[1] - y
                # don't dispatch motion if no button are pressed
                if event.buttons == (0, 0, 0):
                    continue
                self._mouse_x = x
                self._mouse_y = y
                self._mouse_meta = self.modifiers
                self.dispatch("on_mouse_move", x, y, self.modifiers)

            # mouse action
            elif event.type in (pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP):
                self._pygame_update_modifiers()
                x, y = event.pos
                btn = "left"
                if event.button == 3:
                    btn = "right"
                elif event.button == 2:
                    btn = "middle"
                elif event.button == 4:
                    btn = "scrolldown"
                elif event.button == 5:
                    btn = "scrollup"
                elif event.button == 6:
                    btn = "scrollright"
                elif event.button == 7:
                    btn = "scrollleft"
                eventname = "on_mouse_down"
                if event.type == pygame.MOUSEBUTTONUP:
                    eventname = "on_mouse_up"
                self._mouse_x = x
                self._mouse_y = y
                self._mouse_meta = self.modifiers
                self._mouse_btn = btn
                self._mouse_down = eventname == "on_mouse_down"
                self.dispatch(eventname, x, y, btn, self.modifiers)

            # joystick action
            elif event.type == pygame.JOYAXISMOTION:
                self.dispatch("on_joy_axis", event.joy, event.axis, event.value)

            elif event.type == pygame.JOYHATMOTION:
                self.dispatch("on_joy_hat", event.joy, event.hat, event.value)

            elif event.type == pygame.JOYBALLMOTION:
                self.dispatch("on_joy_ball", event.joy, event.ballid, event.rel[0], event.rel[1])

            elif event.type == pygame.JOYBUTTONDOWN:
                self.dispatch("on_joy_button_down", event.joy, event.button)

            elif event.type == pygame.JOYBUTTONUP:
                self.dispatch("on_joy_button_up", event.joy, event.button)

            # keyboard action
            elif event.type in (pygame.KEYDOWN, pygame.KEYUP):
                self._pygame_update_modifiers(event.mod)
                # atm, don't handle keyup
                if event.type == pygame.KEYUP:
                    self.dispatch("on_key_up", event.key, event.scancode)
                    continue

                # don't dispatch more key if down event is accepted
                if self.dispatch("on_key_down", event.key, event.scancode, event.unicode, self.modifiers):
                    continue
                self.dispatch("on_keyboard", event.key, event.scancode, event.unicode, self.modifiers)

            # video resize
            elif event.type == pygame.VIDEORESIZE:
                self._size = event.size
                self.update_viewport()

            elif event.type == pygame.VIDEOEXPOSE:
                self.canvas.ask_update()

            # ignored event
            elif event.type == pygame.ACTIVEEVENT:
                pass

            # drop file (pygame patch needed)
            elif (
                event.type == pygame.USEREVENT
                and hasattr(pygame, "USEREVENT_DROPFILE")
                and event.code == pygame.USEREVENT_DROPFILE
            ):
                self.dispatch("on_dropfile", event.filename)

            """
Exemplo n.º 41
0
    def test_smooth_scroll_end(self):
        EventLoop.ensure_window()
        win = EventLoop.window
        grid = _TestGrid()
        scroll = ScrollView(smooth_scroll_end=10)

        assert scroll.smooth_scroll_end == 10
        scroll.add_widget(grid)

        # XXX this shouldn't be needed, but previous tests apparently
        # don't cleanup
        while win.children:
            win.remove_widget(win.children[0])

        win.add_widget(scroll)

        # get widgets ready
        EventLoop.idle()

        e = scroll.effect_y
        assert e.velocity == 0

        touch = UTMotionEvent(
            "unittest", next(touch_id), {
                "x": scroll.center_x / float(win.width),
                "y": scroll.center_y / float(win.height),
            })

        touch.profile.append('button')
        touch.button = 'scrollup'

        EventLoop.post_dispatch_input("begin", touch)
        # EventLoop.post_dispatch_input("update", touch)
        assert e.velocity == 10 * scroll.scroll_wheel_distance
        EventLoop.idle()
        assert 0 < e.velocity < 10 * scroll.scroll_wheel_distance
        EventLoop.post_dispatch_input("end", touch)
        EventLoop.idle()
        assert 0 < e.velocity < 10 * scroll.scroll_wheel_distance

        # wait for velocity to die off
        while e.velocity:
            EventLoop.idle()

        touch = UTMotionEvent(
            "unittest", next(touch_id), {
                "x": scroll.center_x / float(win.width),
                "y": scroll.center_y / float(win.height),
            })
        touch.profile.append('button')
        touch.button = 'scrolldown'

        EventLoop.post_dispatch_input("begin", touch)
        # EventLoop.post_dispatch_input("update", touch)
        assert e.velocity == -10 * scroll.scroll_wheel_distance
        EventLoop.idle()
        assert 0 > e.velocity > -10 * scroll.scroll_wheel_distance
        EventLoop.post_dispatch_input("end", touch)
        EventLoop.idle()
        assert 0 > e.velocity > -10 * scroll.scroll_wheel_distance
Exemplo n.º 42
0
    def _mainloop(self):
        EventLoop.idle()

        for event in pygame.event.get():

            # kill application (SIG_TERM)
            if event.type == pygame.QUIT:
                EventLoop.quit = True
                self.close()

            # mouse move
            elif event.type == pygame.MOUSEMOTION:
                # don't dispatch motion if no button are pressed
                if event.buttons == (0, 0, 0):
                    continue
                x, y = event.pos
                self.dispatch('on_mouse_move', x, y, self.modifiers)

            # mouse action
            elif event.type in (pygame.MOUSEBUTTONDOWN,
                                pygame.MOUSEBUTTONUP):
                self._pygame_update_modifiers()
                x, y = event.pos
                btn = 'left'
                if event.button == 3:
                    btn = 'right'
                elif event.button == 2:
                    btn = 'middle'
                elif event.button == 4:
                    btn = 'scrolldown'
                elif event.button == 5:
                    btn = 'scrollup'
                eventname = 'on_mouse_down'
                if event.type == pygame.MOUSEBUTTONUP:
                    eventname = 'on_mouse_up'
                self.dispatch(eventname, x, y, btn, self.modifiers)

            # keyboard action
            elif event.type in (pygame.KEYDOWN, pygame.KEYUP):
                self._pygame_update_modifiers(event.mod)
                # atm, don't handle keyup
                if event.type == pygame.KEYUP:
                    self.dispatch('on_key_up', event.key,
                        event.scancode)
                    continue

                # don't dispatch more key if down event is accepted
                if self.dispatch('on_key_down', event.key,
                                 event.scancode, event.unicode,
                                 self.modifiers):
                    continue
                self.dispatch('on_keyboard', event.key,
                              event.scancode, event.unicode,
                              self.modifiers)

            # video resize
            elif event.type == pygame.VIDEORESIZE:
                self._size = event.size
                # don't use trigger here, we want to delay the resize event
                cb = self._do_resize
                Clock.unschedule(cb)
                Clock.schedule_once(cb, .1)

            elif event.type == pygame.VIDEOEXPOSE:
                self.canvas.ask_update()

            # ignored event
            elif event.type == pygame.ACTIVEEVENT:
                pass

            '''
Exemplo n.º 43
0
    def _mainloop(self):
        EventLoop.idle()

        while True:
            event = sdl.poll()
            if event is False:
                break
            if event is None:
                continue

            #print 'sdl received', event
            action, args = event[0], event[1:]
            if action == 'quit':
                EventLoop.quit = True
                self.close()
                break

            elif action in ('fingermotion', 'fingerdown', 'fingerup'):
                # for finger, pass the raw event to SDL motion event provider
                SDLMotionEventProvider.q.appendleft(event)

            if action == 'mousemotion':
                x, y = args
                self.dispatch('on_mouse_move', x, y, self.modifiers)

            elif action in ('mousebuttondown', 'mousebuttonup'):
                x, y, button = args
                btn = 'left'
                if button == 3:
                    btn = 'right'
                elif button == 2:
                    btn = 'middle'
                eventname = 'on_mouse_down'
                if action == 'mousebuttonup':
                    eventname = 'on_mouse_up'
                self.dispatch(eventname, x, y, btn, self.modifiers)

            # video resize
            elif action == 'windowresized':
                self._size = args
                # don't use trigger here, we want to delay the resize event
                cb = self._do_resize
                Clock.unschedule(cb)
                Clock.schedule_once(cb, .1)

            elif action == 'windowresized':
                 self.canvas.ask_update()

            elif action == 'windowminimized':
                self.do_pause()

            elif action == 'windowrestored':
                pass

            elif action in ('keydown', 'keyup'):
                mod, key, scancode, unicode = args

                # XXX ios keyboard suck, when backspace is hit, the delete
                # keycode is sent. fix it.
                if key == 127:
                    key = 8

                self._pygame_update_modifiers(mod)
                if action == 'keyup':
                    self.dispatch('on_key_up', key, scancode)
                    continue

                # don't dispatch more key if down event is accepted
                if self.dispatch('on_key_down', key,
                                 scancode, unicode,
                                 self.modifiers):
                    continue
                self.dispatch('on_keyboard', key,
                              scancode, unicode,
                              self.modifiers)

            elif action == 'textinput':
                key = args[0][0]
                # XXX on IOS, keydown/up don't send unicode anymore.
                # With latest sdl, the text is sent over textinput
                # Right now, redo keydown/up, but we need to seperate both call
                # too. (and adapt on_key_* API.)
                self.dispatch('on_key_down', key, None, args[0],
                              self.modifiers)
                self.dispatch('on_keyboard', None, None, args[0],
                              self.modifiers)
                self.dispatch('on_key_up', key, None, args[0],
                              self.modifiers)
Exemplo n.º 44
0
    def generation_step(self, with_realize = False):
        "Will be called in order to show some advancement"
        i, row, col, face, item = self.index.pop()

        #Determine wheter a new page should be appended

        face_index = 0 if self.current_face == 'F' else 1
        if self.current_face != face:
            self.current_face = face
            self.current_page_num[1-face_index] = i
            self.AddPage()
        elif self.current_page_num[face_index] != i:
            self.current_page_num[face_index] = i
            self.AddPage()


        #Determine Image X/Y/W/H depending on print mode
        if self.mode == 'LAYOUT':
            x, y, self.x, self.y, angle, pageindex = item.layout
            x /= cm(1)
            y /= cm(1)
            self.x /= cm(1)
            self.y /= cm(1)
        elif self.mode == 'BINCAN':
            x, y, self.x, self.y, angle, item = item #hackick: replace item in place !
            x /= cm(1)
            y /= cm(1)
            self.x /= cm(1)
            self.y /= cm(1)
        else:
            if face == 'F':
                x, y = col * self.x + left, height-(1+row)*self.y - top
            else:
                x, y = width - (1+col)*self.x - left - right, height-(1+row)*self.y - top
                #x, y = width - (1+col)*self.x - right, height-(1+row)*self.y - top
            #self.x & slef.y has already been setp by calculate_size
            #Check is there is a layout that could be used, just for the angle
            if getattr(item, 'layout',0):
                angle = item.layout[4]
            else:
                angle = 0

        #Now that in item lies the Stack Item, before rendering it, inject special print vairables
        item.print_index = {
            'pagenum' : i,
            'stackrow': row,
            'stackcol': col,
            'pageface': face
        }

        # Now, define source for image: we either get the source or convert to image
        if item.image:#speicla case for complex image manip

            src = ImageReader(item.image.rotate(angle))
        elif item.template:
            if with_realize:
                item.realise(True,True)
                tmplWidget = item.tmplWidget
            elif item.tmplWidget:#it has been modified
                tmplWidget = item.tmplWidget
            else:
                from template import BGTemplate
                Logger.info( '[Printer] Generation Step without tmplWidget')
                tmplWidget = BGTemplate.FromFile(item.template)
                if tmplWidget:
                    #only taking the last one
                    tmplWidget = tmplWidget[-1]
                else:
                    raise NameError('No such template: '+ item.template)
                if item.values:
                    tmplWidget.apply_values(item.values)
                from kivy.base import EventLoop
                EventLoop.idle()
            cim = tmplWidget.toImage(for_print=True)
            pim = frombuffer('RGBA', cim.size, cim._texture.pixels, 'raw', 'RGBA',0,1)
            src = ImageReader(pim.rotate(angle))
        else:
            src = item.source
            from utils import find_path
            src = find_path(src)
            if angle:
                src = ImageReader(PILOpen(src).rotate(angle))

        #print "Adding Image to pdf", i, row, col, face, item, src, x, y, self.x, self.y, angle
        self.pdf.drawImage(src, x*r_cm, y*r_cm, self.x*r_cm, self.y*r_cm, mask='auto')
        from conf import CP
        if CP.getboolean('Print','draw_cut_rect'):
            #add line after image: they ll be above
            self.AddLines(x,y,self.x,self.y)
Exemplo n.º 45
0
    def _mainloop(self):
        EventLoop.idle()

        # for android/iOS, we don't want to have any event nor executing our
        # main loop while the pause is going on. This loop wait any event (not
        # handled by the event filter), and remove them from the queue.
        # Nothing happen during the pause on iOS, except gyroscope value sended
        # over joystick. So it's safe.
        while self._pause_loop:
            self._win.wait_event()
            if not self._pause_loop:
                break
            self._win.poll()

        while True:
            event = self._win.poll()
            if event is False:
                break
            if event is None:
                continue

            action, args = event[0], event[1:]
            if action == 'quit':
                if self.dispatch('on_request_close'):
                    continue
                EventLoop.quit = True
                self.close()
                break

            elif action in ('fingermotion', 'fingerdown', 'fingerup'):
                # for finger, pass the raw event to SDL motion event provider
                # XXX this is problematic. On OSX, it generates touches with 0,
                # 0 coordinates, at the same times as mouse. But it works.
                # We have a conflict of using either the mouse or the finger.
                # Right now, we have no mechanism that we could use to know
                # which is the preferred one for the application.
                if platform in ('ios', 'android'):
                    SDL2MotionEventProvider.q.appendleft(event)
                pass

            elif action == 'mousemotion':
                x, y = args
                x, y = self._fix_mouse_pos(x, y)
                self._mouse_x = x
                self._mouse_y = y
                # don't dispatch motion if no button are pressed
                if len(self._mouse_buttons_down) == 0:
                    continue
                self._mouse_meta = self.modifiers
                self.dispatch('on_mouse_move', x, y, self.modifiers)

            elif action in ('mousebuttondown', 'mousebuttonup'):
                x, y, button = args
                x, y = self._fix_mouse_pos(x, y)
                btn = 'left'
                if button == 3:
                    btn = 'right'
                elif button == 2:
                    btn = 'middle'
                eventname = 'on_mouse_down'
                self._mouse_buttons_down.add(button)
                if action == 'mousebuttonup':
                    eventname = 'on_mouse_up'
                    self._mouse_buttons_down.remove(button)
                self._mouse_x = x
                self._mouse_y = y
                self.dispatch(eventname, x, y, btn, self.modifiers)
            elif action.startswith('mousewheel'):
                self._update_modifiers()
                x, y, button = args
                btn = 'scrolldown'
                if action.endswith('up'):
                    btn = 'scrollup'
                elif action.endswith('right'):
                    btn = 'scrollright'
                elif action.endswith('left'):
                    btn = 'scrollleft'

                self._mouse_meta = self.modifiers
                self._mouse_btn = btn
                #times = x if y == 0 else y
                #times = min(abs(times), 100)
                #for k in range(times):
                self._mouse_down = True
                self.dispatch('on_mouse_down', self._mouse_x, self._mouse_y,
                              btn, self.modifiers)
                self._mouse_down = False
                self.dispatch('on_mouse_up', self._mouse_x, self._mouse_y, btn,
                              self.modifiers)

            elif action == 'dropfile':
                dropfile = args
                self.dispatch('on_dropfile', dropfile[0])
            # video resize
            elif action == 'windowresized':
                self._size = self._win.window_size
                # don't use trigger here, we want to delay the resize event
                cb = self._do_resize
                Clock.unschedule(cb)
                Clock.schedule_once(cb, .1)

            elif action == 'windowresized':
                self.canvas.ask_update()

            elif action == 'windowrestored':
                self.canvas.ask_update()

            elif action == 'windowexposed':
                self.canvas.ask_update()

            elif action == 'windowminimized':
                if Config.getboolean('kivy', 'pause_on_minimize'):
                    self.do_pause()

            elif action == 'joyaxismotion':
                stickid, axisid, value = args
                self.dispatch('on_joy_axis', stickid, axisid, value)
            elif action == 'joyhatmotion':
                stickid, hatid, value = args
                self.dispatch('on_joy_hat', stickid, hatid, value)
            elif action == 'joyballmotion':
                stickid, ballid, xrel, yrel = args
                self.dispatch('on_joy_ball', stickid, ballid, xrel, yrel)
            elif action == 'joybuttondown':
                stickid, buttonid = args
                self.dispatch('on_joy_button_down', stickid, buttonid)
            elif action == 'joybuttonup':
                stickid, buttonid = args
                self.dispatch('on_joy_button_up', stickid, buttonid)

            elif action in ('keydown', 'keyup'):
                mod, key, scancode, kstr = args

                key_swap = {
                    SDLK_LEFT: 276,
                    SDLK_RIGHT: 275,
                    SDLK_UP: 273,
                    SDLK_DOWN: 274,
                    SDLK_HOME: 278,
                    SDLK_END: 279,
                    SDLK_PAGEDOWN: 281,
                    SDLK_PAGEUP: 280,
                    SDLK_SHIFTR: 303,
                    SDLK_SHIFTL: 304,
                    SDLK_SUPER: 309,
                    SDLK_LCTRL: 305,
                    SDLK_RCTRL: 306,
                    SDLK_LALT: 308,
                    SDLK_RALT: 307,
                    SDLK_CAPS: 301,
                    SDLK_INSERT: 277,
                    SDLK_F1: 282,
                    SDLK_F2: 283,
                    SDLK_F3: 284,
                    SDLK_F4: 285,
                    SDLK_F5: 286,
                    SDLK_F6: 287,
                    SDLK_F7: 288,
                    SDLK_F8: 289,
                    SDLK_F9: 290,
                    SDLK_F10: 291,
                    SDLK_F11: 292,
                    SDLK_F12: 293,
                    SDLK_F13: 294,
                    SDLK_F14: 295,
                    SDLK_F15: 296,
                    SDLK_KEYPADNUM: 300,
                    SDLK_KP_DEVIDE: 267,
                    SDLK_KP_MULTIPLY: 268,
                    SDLK_KP_MINUS: 269,
                    SDLK_KP_PLUS: 270,
                    SDLK_KP_ENTER: 271,
                    SDLK_KP_DOT: 266,
                    SDLK_KP_0: 256,
                    SDLK_KP_1: 257,
                    SDLK_KP_2: 258,
                    SDLK_KP_3: 259,
                    SDLK_KP_4: 260,
                    SDLK_KP_5: 261,
                    SDLK_KP_6: 262,
                    SDLK_KP_7: 263,
                    SDLK_KP_8: 264,
                    SDLK_KP_9: 265
                }

                if platform == 'ios':
                    # XXX ios keyboard suck, when backspace is hit, the delete
                    # keycode is sent. fix it.
                    key_swap[127] = 8  # back

                try:
                    key = key_swap[key]
                except KeyError:
                    pass

                if action == 'keydown':
                    self._update_modifiers(mod, key)
                else:
                    self._update_modifiers(mod)  # ignore the key, it
                    # has been released

                # if mod in self._meta_keys:
                if (key not in self._modifiers
                        and key not in self.command_keys.keys()):
                    try:
                        kstr = unichr(key)
                    except ValueError:
                        pass
                #if 'shift' in self._modifiers and key\
                #        not in self.command_keys.keys():
                #    return

                if action == 'keyup':
                    self.dispatch('on_key_up', key, scancode)
                    continue

                # don't dispatch more key if down event is accepted
                if self.dispatch('on_key_down', key, scancode, kstr,
                                 self.modifiers):
                    continue
                self.dispatch('on_keyboard', key, scancode, kstr,
                              self.modifiers)

            elif action == 'textinput':
                text = args[0]
                self.dispatch('on_textinput', text)

            # unhandled event !
            else:
                Logger.trace('WindowSDL: Unhandled event %s' % str(event))
Exemplo n.º 46
0
 def move_frames(self, t):
     for i in range(t):
         EventLoop.idle()
Exemplo n.º 47
0
 def _run_mc(self, dt):
     del dt
     if self.unittest_verbosity() > 1:
         time.sleep(.05)
     EventLoop.idle()
Exemplo n.º 48
0
    def _mainloop(self):
        EventLoop.idle()

        for event in pygame.event.get():

            # kill application (SIG_TERM)
            if event.type == pygame.QUIT:
                EventLoop.quit = True
                self.close()

            # mouse move
            elif event.type == pygame.MOUSEMOTION:
                x, y = event.pos
                self.mouse_pos = x, self.system_size[1] - y
                # don't dispatch motion if no button are pressed
                if event.buttons == (0, 0, 0):
                    continue
                self._mouse_x = x
                self._mouse_y = y
                self._mouse_meta = self.modifiers
                self.dispatch('on_mouse_move', x, y, self.modifiers)

            # mouse action
            elif event.type in (pygame.MOUSEBUTTONDOWN,
                                pygame.MOUSEBUTTONUP):
                self._pygame_update_modifiers()
                x, y = event.pos
                btn = 'left'
                if event.button == 3:
                    btn = 'right'
                elif event.button == 2:
                    btn = 'middle'
                elif event.button == 4:
                    btn = 'scrolldown'
                elif event.button == 5:
                    btn = 'scrollup'
                elif event.button == 6:
                    btn = 'scrollright'
                elif event.button == 7:
                    btn = 'scrollleft'
                eventname = 'on_mouse_down'
                if event.type == pygame.MOUSEBUTTONUP:
                    eventname = 'on_mouse_up'
                self._mouse_x = x
                self._mouse_y = y
                self._mouse_meta = self.modifiers
                self._mouse_btn = btn
                self._mouse_down = eventname == 'on_mouse_down'
                self.dispatch(eventname, x, y, btn, self.modifiers)

            # keyboard action
            elif event.type in (pygame.KEYDOWN, pygame.KEYUP):
                self._pygame_update_modifiers(event.mod)
                # atm, don't handle keyup
                if event.type == pygame.KEYUP:
                    self.dispatch('on_key_up', event.key,
                        event.scancode)
                    continue

                # don't dispatch more key if down event is accepted
                if self.dispatch('on_key_down', event.key,
                                 event.scancode, event.unicode,
                                 self.modifiers):
                    continue
                self.dispatch('on_keyboard', event.key,
                              event.scancode, event.unicode,
                              self.modifiers)

            # video resize
            elif event.type == pygame.VIDEORESIZE:
                self._size = event.size
                self.update_viewport()

            elif event.type == pygame.VIDEOEXPOSE:
                self.canvas.ask_update()

            # ignored event
            elif event.type == pygame.ACTIVEEVENT:
                pass

            # drop file (pygame patch needed)
            elif event.type == pygame.USEREVENT and \
                hasattr(pygame, 'USEREVENT_DROPFILE') and \
                event.code == pygame.USEREVENT_DROPFILE:
                self.dispatch('on_dropfile', event.filename)

            '''
Exemplo n.º 49
0
    def _mainloop(self):
        EventLoop.idle()

        # for android/iOS, we don't want to have any event nor executing our
        # main loop while the pause is going on. This loop wait any event (not
        # handled by the event filter), and remove them from the queue.
        # Nothing happen during the pause on iOS, except gyroscope value sent
        # over joystick. So it's safe.
        while self._pause_loop:
            self._win.wait_event()
            if not self._pause_loop:
                break
            self._win.poll()

        while True:
            event = self._win.poll()
            if event is False:
                break
            if event is None:
                continue

            action, args = event[0], event[1:]
            if action == 'quit':
                if self.dispatch('on_request_close'):
                    continue
                EventLoop.quit = True
                self.close()
                break

            elif action in ('fingermotion', 'fingerdown', 'fingerup'):
                # for finger, pass the raw event to SDL motion event provider
                # XXX this is problematic. On OSX, it generates touches with 0,
                # 0 coordinates, at the same times as mouse. But it works.
                # We have a conflict of using either the mouse or the finger.
                # Right now, we have no mechanism that we could use to know
                # which is the preferred one for the application.
                if platform in ('ios', 'android'):
                    SDL2MotionEventProvider.q.appendleft(event)
                pass

            elif action == 'mousemotion':
                x, y = args
                x, y = self._fix_mouse_pos(x, y)
                self._mouse_x = x
                self._mouse_y = y
                # don't dispatch motion if no button are pressed
                if len(self._mouse_buttons_down) == 0:
                    continue
                self._mouse_meta = self.modifiers
                self.dispatch('on_mouse_move', x, y, self.modifiers)

            elif action in ('mousebuttondown', 'mousebuttonup'):
                x, y, button = args
                x, y = self._fix_mouse_pos(x, y)
                btn = 'left'
                if button == 3:
                    btn = 'right'
                elif button == 2:
                    btn = 'middle'
                eventname = 'on_mouse_down'
                self._mouse_buttons_down.add(button)
                if action == 'mousebuttonup':
                    eventname = 'on_mouse_up'
                    self._mouse_buttons_down.remove(button)
                self._mouse_x = x
                self._mouse_y = y
                self.dispatch(eventname, x, y, btn, self.modifiers)
            elif action.startswith('mousewheel'):
                self._update_modifiers()
                x, y, button = args
                btn = 'scrolldown'
                if action.endswith('up'):
                    btn = 'scrollup'
                elif action.endswith('right'):
                    btn = 'scrollright'
                elif action.endswith('left'):
                    btn = 'scrollleft'

                self._mouse_meta = self.modifiers
                self._mouse_btn = btn
                #times = x if y == 0 else y
                #times = min(abs(times), 100)
                #for k in range(times):
                self._mouse_down = True
                self.dispatch('on_mouse_down',
                    self._mouse_x, self._mouse_y, btn, self.modifiers)
                self._mouse_down = False
                self.dispatch('on_mouse_up',
                    self._mouse_x, self._mouse_y, btn, self.modifiers)

            elif action == 'dropfile':
                dropfile = args
                self.dispatch('on_dropfile', dropfile[0])
            # video resize
            elif action == 'windowresized':
                self._size = self._win.window_size
                # don't use trigger here, we want to delay the resize event
                ev = self._do_resize_ev
                if ev is None:
                    ev = self._do_resize_ev = Clock.schedule_once(self._do_resize, .1)
                else:
                    ev()

            elif action == 'windowresized':
                self.canvas.ask_update()

            elif action == 'windowrestored':
                self.dispatch('on_restore')
                self.canvas.ask_update()

            elif action == 'windowexposed':
                self.canvas.ask_update()

            elif action == 'windowminimized':
                self.dispatch('on_minimize')
                if Config.getboolean('kivy', 'pause_on_minimize'):
                    self.do_pause()

            elif action == 'windowmaximized':
                self.dispatch('on_maximize')

            elif action == 'windowhidden':
                self.dispatch('on_hide')

            elif action == 'windowshown':
                self.dispatch('on_show')

            elif action == 'windowfocusgained':
                self._focus = True

            elif action == 'windowfocuslost':
                self._focus = False

            elif action == 'windowenter':
                self.dispatch('on_cursor_enter')

            elif action == 'windowleave':
                self.dispatch('on_cursor_leave')

            elif action == 'joyaxismotion':
                stickid, axisid, value = args
                self.dispatch('on_joy_axis', stickid, axisid, value)
            elif action == 'joyhatmotion':
                stickid, hatid, value = args
                self.dispatch('on_joy_hat', stickid, hatid, value)
            elif action == 'joyballmotion':
                stickid, ballid, xrel, yrel = args
                self.dispatch('on_joy_ball', stickid, ballid, xrel, yrel)
            elif action == 'joybuttondown':
                stickid, buttonid = args
                self.dispatch('on_joy_button_down', stickid, buttonid)
            elif action == 'joybuttonup':
                stickid, buttonid = args
                self.dispatch('on_joy_button_up', stickid, buttonid)

            elif action in ('keydown', 'keyup'):
                mod, key, scancode, kstr = args

                try:
                    key = self.key_map[key]
                except KeyError:
                    pass

                if action == 'keydown':
                    self._update_modifiers(mod, key)
                else:
                    self._update_modifiers(mod)  # ignore the key, it
                                                 # has been released

                # if mod in self._meta_keys:
                if (key not in self._modifiers and
                    key not in self.command_keys.keys()):
                    try:
                        kstr = unichr(key)
                    except ValueError:
                        pass
                #if 'shift' in self._modifiers and key\
                #        not in self.command_keys.keys():
                #    return

                if action == 'keyup':
                    self.dispatch('on_key_up', key, scancode)
                    continue

                # don't dispatch more key if down event is accepted
                if self.dispatch('on_key_down', key,
                                 scancode, kstr,
                                 self.modifiers):
                    continue
                self.dispatch('on_keyboard', key,
                              scancode, kstr,
                              self.modifiers)

            elif action == 'textinput':
                text = args[0]
                self.dispatch('on_textinput', text)

            # unhandled event !
            else:
                Logger.trace('WindowSDL: Unhandled event %s' % str(event))
Exemplo n.º 50
0
    def _mainloop(self):
        EventLoop.idle()

        while True:
            event = self._win.poll()
            if event is False:
                break
            if event is None:
                continue

            action, args = event[0], event[1:]
            if action == 'quit':
                EventLoop.quit = True
                self.close()
                break

            elif action in ('fingermotion', 'fingerdown', 'fingerup'):
                # for finger, pass the raw event to SDL motion event provider
                SDL2MotionEventProvider.q.appendleft(event)

            if action == 'mousemotion':
                x, y = args
                self.mouse_pos = x, self.system_size[1] - y
                # don't dispatch motion if no button are pressed
                self._mouse_x = x
                self._mouse_y = y
                self._mouse_meta = self.modifiers
                self.dispatch('on_mouse_move', x, y, self.modifiers)

            elif action in ('mousebuttondown', 'mousebuttonup'):
                x, y, button = args
                btn = 'left'
                if button == 3:
                    btn = 'right'
                elif button == 2:
                    btn = 'middle'
                eventname = 'on_mouse_down'
                if action == 'mousebuttonup':
                    eventname = 'on_mouse_up'
                self.dispatch(eventname, x, y, btn, self.modifiers)
            elif action.startswith('mousewheel'):
                self._update_modifiers()
                x, y, button = args
                btn = 'scrolldown'
                if action.endswith('up'):
                    btn = 'scrollup'
                elif action.endswith('right'):
                    btn = 'scrollright'
                elif action.endswith('left'):
                    btn = 'scrollleft'

                self._mouse_meta = self.modifiers
                self._mouse_btn = btn
                #times = x if y == 0 else y
                #times = min(abs(times), 100)
                #for k in range(times):
                self._mouse_down = True
                self.dispatch('on_mouse_down',
                    self._mouse_x, self._mouse_y, btn, self.modifiers)
                self._mouse_down = False
                self.dispatch('on_mouse_up',
                    self._mouse_x, self._mouse_y, btn, self.modifiers)

            elif action == 'dropfile':
                dropfile = args
                self.dispatch('on_dropfile', dropfile[0])
            # video resize
            elif action == 'windowresized':
                self._size = args
                # don't use trigger here, we want to delay the resize event
                cb = self._do_resize
                Clock.unschedule(cb)
                Clock.schedule_once(cb, .1)

            elif action == 'windowresized':
                self.canvas.ask_update()

            elif action == 'windowrestored':
                self.canvas.ask_update()

            elif action == 'windowminimized':
                self.do_pause()

            elif action == 'joyaxismotion':
                stickid, axisid, value = args
                self.dispatch('on_joy_axis', stickid, axisid, value)
            elif action == 'joyhatmotion':
                stickid, hatid, value = args
                self.dispatch('on_joy_hat', stickid, hatid, value)
            elif action == 'joyballmotion':
                stickid, ballid, xrel, yrel = args
                self.dispatch('on_joy_ball', stickid, ballid, xrel, yrel)
            elif action == 'joybuttondown':
                stickid, buttonid = args
                self.dispatch('on_joy_button_down', stickid, buttonid)
            elif action == 'joybuttonup':
                stickid, buttonid = args
                self.dispatch('on_joy_button_up', stickid, buttonid)
                
            elif action in ('keydown', 'keyup'):
                mod, key, scancode, kstr = args
                if mod in self._meta_keys:
                    try:
                        kstr = unichr(key)
                    except ValueError:
                        pass

                # XXX ios keyboard suck, when backspace is hit, the delete
                # keycode is sent. fix it.
                key_swap = {127: 8,  # back
                            SDLK_LEFT: 276,
                            SDLK_RIGHT: 275,
                            SDLK_UP: 273,
                            SDLK_DOWN: 274,
                            SDLK_HOME: 278,
                            SDLK_END: 279,
                            SDLK_PAGEDOWN: 281,
                            SDLK_PAGEUP: 280,
                            SDLK_SHIFTL: 303,
                            SDLK_SHIFTR: 304}
                try:
                    key = key_swap[key]
                except KeyError:
                    pass

                self._update_modifiers(mod)
                if action == 'keyup':
                    self.dispatch('on_key_up', key, scancode)
                    continue

                # don't dispatch more key if down event is accepted
                if self.dispatch('on_key_down', key,
                                 scancode, kstr,
                                 self.modifiers):
                    continue
                self.dispatch('on_keyboard', key,
                              scancode, kstr,
                              self.modifiers)

            elif action == 'textinput':
                key = args[0][0]
                # XXX on IOS, keydown/up don't send unicode anymore.
                # With latest sdl, the text is sent over textinput
                # Right now, redo keydown/up, but we need to seperate both call
                # too. (and adapt on_key_* API.)
                self.dispatch('on_key_down', key, None, args[0],
                              self.modifiers)
                self.dispatch('on_keyboard', None, None, args[0],
                              self.modifiers)
                self.dispatch('on_key_up', key, None, args[0],
                              self.modifiers)
Exemplo n.º 51
0
 def inner(*args):
     from kivy.base import EventLoop
     EventLoop.idle()
     cim = tmpl.toImage()
     cim.texture.flip_vertical()
     self.ids['img'].texture = cim.texture
Exemplo n.º 52
0
    def test_touch_draw(self):
        # get Window instance for creating visible
        # widget tree and for calculating coordinates
        EventLoop.ensure_window()
        win = EventLoop.window

        # add widget for testing
        child = WidgetCanvasDraw()
        win.add_widget(child)

        # get widgets ready
        EventLoop.idle()

        # default "cursor" position in the middle
        pos = [win.width / 2.0, win.height / 2.0]

        # default pos, new pos
        points = [
            [pos[0] - 5, pos[1], pos[0] + 5, pos[1]],
            [pos[0], pos[1] - 5, pos[0], pos[1] + 5]
        ]

        # general behavior for touch+move+release
        for i, point in enumerate(points):
            x, y, nx, ny = point

            # create custom MotionEvent (touch) instance
            touch = UTMotionEvent("unittest", 1, {
                "sx": x / float(win.width),
                "sy": y / float(win.height),
            })

            # dispatch the MotionEvent in EventLoop as
            # touch/press/click, see Profiles for more info:
            # https://kivy.org/docs/api-kivy.input.motionevent.html#profiles
            EventLoop.post_dispatch_input("begin", touch)

            # the touch is dispatched and has ud['lines']
            # available from on_touch_down
            self.assertIn('lines', touch.ud)
            self.assertTrue(isinstance(touch.ud['lines'], Point))

            # move touch from current to the new position
            touch.move({
                "sx": nx / float(win.width),
                "sy": ny / float(win.height)
            })
            # update the MotionEvent in EventLoop
            EventLoop.post_dispatch_input("update", touch)

            # release the MotionEvent in EventLoop
            EventLoop.post_dispatch_input("end", touch)

            # still available, but released
            self.assertIn('lines', touch.ud)
            self.assertTrue(isinstance(touch.ud['lines'], Point))

            expected_points = [[
                x + 0, y, x + 1, y,
                x + 2, y, x + 3, y,
                x + 4, y, x + 5, y,
                x + 6, y, x + 7, y,
                x + 8, y, x + 9, y
            ], [
                x, y + 0, x, y + 1,
                x, y + 2, x, y + 3,
                x, y + 4, x, y + 5,
                x, y + 6, x, y + 7,
                x, y + 8, x, y + 9
            ]]

            # check if the instruction points == expected ones
            self.assertEqual(
                touch.ud['lines'].points,
                expected_points[i]
            )

        # render the graphics
        self.render(child)
Exemplo n.º 53
0
 def magic_fill(self):
     #alas, I have to linezarise in order to save layout for each widget
     from kivy.app import App
     from kivy.base import EventLoop
     from kivy.uix.label import Label
     from utils import alert
     print 'linearize deck',
     alert('Linearizing Deck')
     EventLoop.idle()
     App.get_running_app().root.ids.deck.linearize(progressbar=self.ids.progress)
     print 'done'
     init_pi = self.page_index
     from conf import page_format
     SIZE = page_format.width-page_format.left-page_format.right, page_format.height-page_format.top-page_format.bottom
     print 'calculating stack size'
     alert('Calculating Size')
     EventLoop.idle()
     #first create tuple of fg/bg
     fg,bg,dual_dict = self.get_duals()
     #fill current page with what you can
     def skey(item):
         w,h = item[0].stack.getSize()
         return w*h, -item[1]
     self.ids.progress.max = len(fg)
     self.ids.progress.value = 1
     from kivy.clock import Clock
     alert('Sorting Layouts by size')
     EventLoop.idle()
     print 'sorting layout'
     fg = sorted(fg, key=skey, reverse=True)
     def inner(*args):
         from utils import alert
         if not fg:
             Clock.unschedule(inner)
             from utils import alert
             alert('Book created')
             self.export_phs()
             from kivy.uix.widget import WidgetException
             try:
                 self.set_page("Page %d"%(init_pi+1))
             except WidgetException,Err:
                 print 'FATAL: Error in Setting page ???',Err
             return
         alert('Organizing Layout on Page %d'%(len(self.pages)))
         EventLoop.idle()
         print 'Organizing Layout on Page %d'%(len(self.pages))
         sorted_phs = fg[:]
         added_ones = list()
         PAGE_LAYOUT = BinCanNode(0, 0, SIZE[0], SIZE[1])
         for f, i in sorted_phs:
             layout = PAGE_LAYOUT.find(f, *f.stack.getSize())
             if not layout:
                 continue
             del fg[fg.index((f, i))]
             added_ones.append(f)
             self.ids.progress.value += 1
             ph = self.add_ph()
             self.set_ph_img(ph, f, use_img_size= True)
             X, Y = layout.x, layout.y
             #Rebase properly
             ph.x = X + page_format.left
             ph.top = page_format.height-page_format.top-Y
             ph.angle = layout.retry.get(ph, 0) * 90
             ph.layout = [ph.x,ph.y,ph.width,ph.height,ph.angle, self.page_index]
         if not added_ones: #We could NOT feet any of the pictures: raise error:
             print 'Error: not pictures could be fit inside one page'
             from utils import alert
             alert('No more pictures can fit on page')
             Clock.unschedule(inner)
             return
         if dual_dict:
             #First page is done, create dual
             mp = self.add_mirror_page()
             for ph, b in zip (reversed(mp.children), [dual_dict[f] for f in added_ones]):
                 #print 'settings back for', ph, b, b.stack.source
                 self.set_ph_img(ph,b, use_img_size= False) # Is it interesting: this will force that front & back have exact same size, depending on front size
         #Add a new page, only if necessay:
         if fg:
             self.add_page()
         #now loop on remaining fg/bg
         Clock.schedule_once(inner,.1)
Exemplo n.º 54
0
    def test_slider_move(self):
        EventLoop.ensure_window()
        win = EventLoop.window
        layout = BoxLayout(orientation='vertical')

        s_handle = TestSliderHandle()
        s_all = TestSliderAll()
        layout.add_widget(s_handle)
        layout.add_widget(s_all)
        win.add_widget(layout)

        # get widgets ready
        EventLoop.idle()

        cur1 = s_handle.children[0]
        cur2 = s_all.children[0]

        h1 = cur1.to_window(*cur1.center)[1]
        h2 = h1 - s_handle.cursor_height
        h3 = cur2.to_window(*cur2.center)[1]
        h4 = h3 - s_all.cursor_height

        w1 = cur1.to_window(*cur1.center)[0]
        w2 = cur2.to_window(*cur2.center)[0]
        wh = win.width / 2.0
        dt = 2

        # default pos, new pos, slider ID
        points = [
            [w1, h1, wh, h1, 'handle'],
            [w1, h2, wh, h2, 'handle'],
            [w2, h3, wh, h3, 'all'],
            [w2, h4, wh, h4, 'all'],
        ]

        for point in points:
            x, y, nx, ny, id = point

            # custom touch
            touch = UTMotionEvent("unittest", 1, {
                "x": x / float(win.width),
                "y": y / float(win.height),
            })

            # touch down
            EventLoop.post_dispatch_input("begin", touch)

            if id == 'handle':
                # touch on handle
                if x == w1 and y == h1:
                    self.assertAlmostEqual(
                        s_handle.value, 0.0,
                        delta=dt
                    )
                # touch in widget area (ignored, previous value)
                elif x == w1 and y == h2:
                    self.assertAlmostEqual(
                        s_handle.value, 50.0,
                        delta=dt
                    )
            elif id == 'all':
                # touch on handle:
                if x == w1 and y == h3:
                    self.assertAlmostEqual(
                        s_all.value, 0.0,
                        delta=dt
                    )
                # touch in widget area
                elif x == w1 and y == h4:
                    self.assertAlmostEqual(
                        s_all.value, 0.0,
                        delta=dt
                    )

            # move from default to new pos
            touch.move({
                "x": nx / float(win.width),
                "y": ny / float(win.height)
            })
            EventLoop.post_dispatch_input("update", touch)

            if id == 'handle':
                # move from handle to center
                if nx == wh and ny == h1:
                    self.assertAlmostEqual(
                        s_handle.value, 50.0,
                        delta=dt
                    )
                # move to center (ignored, previous value)
                elif nx == wh and ny == h2:
                    self.assertAlmostEqual(
                        s_handle.value, 50.0,
                        delta=dt
                    )
            elif id == 'all':
                # touch on handle:
                if nx == wh and ny == h3:
                    self.assertAlmostEqual(
                        s_all.value, 50.0,
                        delta=dt
                    )
                # touch in widget area
                elif nx == wh and ny == h4:
                    self.assertAlmostEqual(
                        s_all.value, 50.0,
                        delta=dt
                    )

            # touch up
            EventLoop.post_dispatch_input("end", touch)

        self.render(layout)
Exemplo n.º 55
0
    def magic_fill(self):
        #alas, I have to linezarise in order to save layout for each widget
        from kivy.app import App
        from kivy.base import EventLoop
        from kivy.uix.label import Label
        from utils import alert
        print 'linearize deck',
        alert('Linearizing Deck')
        EventLoop.idle()
        App.get_running_app().root.ids.deck.linearize(
            progressbar=self.ids.progress)
        print 'done'
        init_pi = self.page_index
        from conf import page_format
        SIZE = page_format.width - page_format.left - page_format.right, page_format.height - page_format.top - page_format.bottom
        print 'calculating stack size'
        alert('Calculating Size')
        EventLoop.idle()
        #first create tuple of fg/bg
        fg, bg, dual_dict = self.get_duals()

        #fill current page with what you can
        def skey(item):
            w, h = item[0].stack.getSize()
            return w * h, -item[1]

        self.ids.progress.max = len(fg)
        self.ids.progress.value = 1
        from kivy.clock import Clock
        alert('Sorting Layouts by size')
        EventLoop.idle()
        print 'sorting layout'
        fg = sorted(fg, key=skey, reverse=True)

        def inner(*args):
            from utils import alert
            if not fg:
                Clock.unschedule(inner)
                from utils import alert
                alert('Book created')
                self.export_phs()
                from kivy.uix.widget import WidgetException
                try:
                    self.set_page("Page %d" % (init_pi + 1))
                except WidgetException, Err:
                    print 'FATAL: Error in Setting page ???', Err
                return
            alert('Organizing Layout on Page %d' % (len(self.pages)))
            EventLoop.idle()
            print 'Organizing Layout on Page %d' % (len(self.pages))
            sorted_phs = fg[:]
            added_ones = list()
            PAGE_LAYOUT = BinCanNode(0, 0, SIZE[0], SIZE[1])
            for f, i in sorted_phs:
                layout = PAGE_LAYOUT.find(f, *f.stack.getSize())
                if not layout:
                    continue
                del fg[fg.index((f, i))]
                added_ones.append(f)
                self.ids.progress.value += 1
                ph = self.add_ph()
                self.set_ph_img(ph, f, use_img_size=True)
                X, Y = layout.x, layout.y
                #Rebase properly
                ph.x = X + page_format.left
                ph.top = page_format.height - page_format.top - Y
                ph.angle = layout.retry.get(ph, 0) * 90
                ph.layout = [
                    ph.x, ph.y, ph.width, ph.height, ph.angle, self.page_index
                ]
            if not added_ones:  #We could NOT feet any of the pictures: raise error:
                print 'Error: not pictures could be fit inside one page'
                from utils import alert
                alert('No more pictures can fit on page')
                Clock.unschedule(inner)
                return
            if dual_dict:
                #First page is done, create dual
                mp = self.add_mirror_page()
                for ph, b in zip(reversed(mp.children),
                                 [dual_dict[f] for f in added_ones]):
                    #print 'settings back for', ph, b, b.stack.source
                    self.set_ph_img(
                        ph, b, use_img_size=False
                    )  # Is it interesting: this will force that front & back have exact same size, depending on front size
            #Add a new page, only if necessay:
            if fg:
                self.add_page()
            #now loop on remaining fg/bg
            Clock.schedule_once(inner, .1)
Exemplo n.º 56
0
 def _run_mc(self):
     EventLoop.idle()
Exemplo n.º 57
0
    def _mainloop(self):
        EventLoop.idle()

        for event in pygame.event.get():

            # kill application (SIG_TERM)
            if event.type == pygame.QUIT:
                EventLoop.quit = True
                self.close()

            # mouse move
            elif event.type == pygame.MOUSEMOTION:
                # don't dispatch motion if no button are pressed
                if event.buttons == (0, 0, 0):
                    continue
                x, y = event.pos
                self.dispatch('on_mouse_move', x, y, self.modifiers)

            # mouse action
            elif event.type in (pygame.MOUSEBUTTONDOWN,
                                pygame.MOUSEBUTTONUP):
                self._pygame_update_modifiers()
                x, y = event.pos
                btn = 'left'
                if event.button == 3:
                    btn = 'right'
                elif event.button == 2:
                    btn = 'middle'
                eventname = 'on_mouse_down'
                if event.type == pygame.MOUSEBUTTONUP:
                    eventname = 'on_mouse_up'
                self.dispatch(eventname, x, y, btn, self.modifiers)

            # keyboard action
            elif event.type in (pygame.KEYDOWN, pygame.KEYUP):
                self._pygame_update_modifiers(event.mod)
                # atm, don't handle keyup
                if event.type == pygame.KEYUP:
                    self.dispatch('on_key_up', event.key,
                        event.scancode)
                    continue

                # don't dispatch more key if down event is accepted
                if self.dispatch('on_key_down', event.key,
                                    event.scancode, event.unicode, event.mod):
                    continue
                self.dispatch('on_keyboard', event.key,
                                    event.scancode, event.unicode, event.mod)

            # video resize
            elif event.type == pygame.VIDEORESIZE:
                self._size = event.size
                # don't use trigger here, we want to delay the resize event
                cb = self._do_resize
                Clock.unschedule(cb)
                Clock.schedule_once(cb, .1)

            elif event.type == pygame.VIDEOEXPOSE:
                self.canvas.ask_update()

            # ignored event
            elif event.type == pygame.ACTIVEEVENT:
                pass

            # unhandled event !
            else:
                Logger.debug('WinPygame: Unhandled event %s' % str(event))