示例#1
0
    def create_window(self, params):
        if self.__glut_window is None:
            # init GLUT !
            pymt_logger.debug('WinGlut: GLUT initialization')
            glutInit('')
            glutInitDisplayMode(
                GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH |
                GLUT_MULTISAMPLE | GLUT_STENCIL | GLUT_ACCUM)

            # create the window
            self.__glut_window = glutCreateWindow('pymt')

        # register all callbcaks
        glutReshapeFunc(self._glut_reshape)
        glutMouseFunc(self._glut_mouse)
        glutMotionFunc(self._glut_mouse_motion)
        glutKeyboardFunc(self._glut_keyboard)

        # update window size
        glutShowWindow()
        self.size = params['width'], params['height']
        if params['fullscreen']:
            pymt_logger.debug('WinGlut: Set window to fullscreen mode')
            glutFullScreen()

        super(MTWindowGlut, self).create_window(params)
示例#2
0
文件: __init__.py 项目: Markitox/pymt
 def _copy_to_gpu(self):
     '''Copy the the buffer into the texture'''
     if self._texture is None:
         pymt_logger.debug('Camera: copy_to_gpu() failed, _texture is None !')
         return
     self._texture.blit_buffer(self._buffer, format=self._format)
     self._buffer = None
示例#3
0
def resource_add_path(path):
    '''Add a custom path to search in
    '''
    if path in resource_paths:
        return
    pymt_logger.debug('Resource: add <%s> in path list' % path)
    resource_paths.append(path)
示例#4
0
    def create_window(self, params):
        if self.__glut_window is None:
            # init GLUT !
            pymt_logger.debug('WinGlut: GLUT initialization')
            glutInit('')
            if 'PYMT_GLUT_UNITTEST' in os.environ:
                glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE)
            else:
                glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA
                                    | GLUT_DEPTH | GLUT_MULTISAMPLE
                                    | GLUT_STENCIL | GLUT_ACCUM)

            # create the window
            self.__glut_window = glutCreateWindow('pymt')

        # register all callbcaks
        glutReshapeFunc(self._glut_reshape)
        glutMouseFunc(self._glut_mouse)
        glutMotionFunc(self._glut_mouse_motion)
        glutKeyboardFunc(self._glut_keyboard)

        # update window size
        glutShowWindow()
        self.size = params['width'], params['height']
        if params['fullscreen']:
            pymt_logger.debug('WinGlut: Set window to fullscreen mode')
            glutFullScreen()

        super(MTWindowGlut, self).create_window(params)
示例#5
0
def resource_add_path(path):
    '''Add a custom path to search in
    '''
    if path in resource_paths:
        return
    pymt_logger.debug('Resource: add <%s> in path list' % path)
    resource_paths.append(path)
示例#6
0
    def _mainloop(self):
        evloop = getEventLoop()
        evloop.idle()

        for event in pygame.event.get():

            # kill application (SIG_TERM)
            if event.type == pygame.QUIT:
                evloop.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_event('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_event(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_event('on_key_up', event.key, event.scancode)
                    continue

                # don't dispatch more key if down event is accepted
                if self.dispatch_event('on_key_down', event.key,
                                       event.scancode, event.unicode):
                    continue
                self.dispatch_event('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:
                pymt_logger.debug('WinPygame: Unhandled event %s' % str(event))
示例#7
0
 def _on_gst_message(self, bus, message):
     t = message.type
     if t == gst.MESSAGE_EOS:
         self._data.set_state(gst.STATE_NULL)
         self.stop()
     elif t == gst.MESSAGE_ERROR:
         self._data.set_state(gst.STATE_NULL)
         err, debug = message.parse_error()
         pymt_logger.error('AudioGstreamer: %s' % err)
         pymt_logger.debug(str(debug))
         self.stop()
示例#8
0
 def _on_gst_message(self, bus, message):
     t = message.type
     if t == gst.MESSAGE_EOS:
         self._data.set_state(gst.STATE_NULL)
         self.stop()
     elif t == gst.MESSAGE_ERROR:
         self._data.set_state(gst.STATE_NULL)
         err, debug = message.parse_error()
         pymt_logger.error('AudioGstreamer: %s' % err)
         pymt_logger.debug(str(debug))
         self.stop()
示例#9
0
文件: shader.py 项目: Markitox/pymt
 def create_shader(self, source, shadertype):
     shader = glCreateShader(shadertype)
     # PyOpenGL bug ? He's waiting for a list of string, not a string
     # on some card, it failed :)
     if isinstance(source, basestring):
         source = [source]
     glShaderSource(shader, source)
     glCompileShader(shader)
     message = self.get_shader_log(shader)
     if message:
         pymt_logger.debug('Shader: shader message: %s' % message)
     return shader
示例#10
0
文件: shader.py 项目: gavine199/pymt
 def create_shader(self, source, shadertype):
     shader = glCreateShader(shadertype)
     # PyOpenGL bug ? He's waiting for a list of string, not a string
     # on some card, it failed :)
     if isinstance(source, basestring):
         source = [source]
     glShaderSource(shader, source)
     glCompileShader(shader)
     message = self.get_shader_log(shader)
     if message:
         pymt_logger.debug('Shader: shader message: %s' % message)
     return shader
示例#11
0
文件: oscAPI.py 项目: Markitox/pymt
def listen(ipAddr='127.0.0.1', port=9001):
    '''Creates a new thread listening to that port
    defaults to ipAddr='127.0.0.1', port 9001
    '''
    global oscThreads
    id = '%s:%d' % (ipAddr, port)
    if id in oscThreads:
        return
    pymt_logger.debug('OSC: Start thread <%s>' % id)
    oscThreads[id] = OSCServer(ipAddr=ipAddr, port=port)
    oscThreads[id].start()
    return id
示例#12
0
def listen(ipAddr='127.0.0.1', port=9001):
    '''Creates a new thread listening to that port
    defaults to ipAddr='127.0.0.1', port 9001
    '''
    global oscThreads
    id = '%s:%d' % (ipAddr, port)
    if id in oscThreads:
        return
    pymt_logger.debug('OSC: Start thread <%s>' % id)
    oscThreads[id] = OSCServer(ipAddr=ipAddr, port=port)
    oscThreads[id].start()
    return id
示例#13
0
def css_reload():
    pymt_logger.debug('CSS: Reloading CSS in progress')
    pymt_sheet.reset()
    for callback, args in _css_sources[:]:
        callback(*args, _reload=True)
    Cache.remove('pymt.css')
    for r in _css_widgets.copy():
        o = r()
        if o is None:
            _css_widgets.remove(r)
            continue
        o.reload_css()
    pymt_logger.info('CSS: CSS Reloaded')
示例#14
0
def dontListen(id=None):
    '''closes the socket and kills the thread
    '''
    global oscThreads
    if id and id in oscThreads:
        ids = [id]
    else:
        ids = oscThreads.keys()
    for id in ids:
        #oscThreads[id].socket.close()
        pymt_logger.debug('OSC: Stop thread <%s>' % id)
        oscThreads[id].isRunning = False
        oscThreads[id].join()
        pymt_logger.debug('OSC: Stop thread <%s> finished' % id)
        del oscThreads[id]
示例#15
0
    def __init__(self, config, win):
        super(Sleep, self).__init__()
        self.timer_no_activity = time()
        self.win = win
        self.step = -1

        # take configuration
        ramp = config.get('ramp').split(':')
        sleep = config.get('sleep').split(':')
        if len(ramp) != len(sleep):
            raise ValueError('Sleep: Invalid ramp/sleep: list size is not the same')
        self.ramp = map(float, ramp)
        self.sleep = map(float, sleep)
        pymt_logger.debug('Sleep: ramp is %s' % str(self.ramp))
        pymt_logger.debug('Sleep: sleep is %s' % str(self.sleep))
示例#16
0
文件: oscAPI.py 项目: Markitox/pymt
def dontListen(id = None):
    '''closes the socket and kills the thread
    '''
    global oscThreads
    if id and id in oscThreads:
        ids = [id]
    else:
        ids = oscThreads.keys()
    for id in ids:
        #oscThreads[id].socket.close()
        pymt_logger.debug('OSC: Stop thread <%s>' % id)
        oscThreads[id].isRunning = False
        oscThreads[id].join()
        pymt_logger.debug('OSC: Stop thread <%s> finished' % id)
        del oscThreads[id]
示例#17
0
    def __init__(self, config, win):
        super(Sleep, self).__init__()
        self.timer_no_activity = time()
        self.win = win
        self.step = -1

        # take configuration
        ramp = config.get('ramp').split(':')
        sleep = config.get('sleep').split(':')
        if len(ramp) != len(sleep):
            raise ValueError(
                'Sleep: Invalid ramp/sleep: list size is not the same')
        self.ramp = map(float, ramp)
        self.sleep = map(float, sleep)
        pymt_logger.debug('Sleep: ramp is %s' % str(self.ramp))
        pymt_logger.debug('Sleep: sleep is %s' % str(self.sleep))
示例#18
0
文件: shader.py 项目: Markitox/pymt
    def __init__(self, vertex_source=None, fragment_source=None):
        self.program = glCreateProgram()

        if vertex_source:
            self.vertex_shader = self.create_shader(
                vertex_source, GL_VERTEX_SHADER)
            glAttachShader(self.program, self.vertex_shader)

        if fragment_source:
            self.fragment_shader = self.create_shader(
                fragment_source, GL_FRAGMENT_SHADER)
            glAttachShader(self.program, self.fragment_shader)

        glLinkProgram(self.program)
        message = self.get_program_log(self.program)
        if message:
            pymt_logger.debug('Shader: shader program message: %s' % message)
示例#19
0
文件: shader.py 项目: gavine199/pymt
    def __init__(self, vertex_source=None, fragment_source=None):
        self.program = glCreateProgram()

        if vertex_source:
            self.vertex_shader = self.create_shader(vertex_source,
                                                    GL_VERTEX_SHADER)
            glAttachShader(self.program, self.vertex_shader)

        if fragment_source:
            self.fragment_shader = self.create_shader(fragment_source,
                                                      GL_FRAGMENT_SHADER)
            glAttachShader(self.program, self.fragment_shader)

        glLinkProgram(self.program)
        message = self.get_program_log(self.program)
        if message:
            pymt_logger.debug('Shader: shader program message: %s' % message)
示例#20
0
文件: svg.py 项目: Markitox/pymt
    def _set_filename(self, filename):
        global squirtle
        if squirtle is None:
            import squirtle
		# TODO remove this ugly code, improve loader for this
        try:
            pymt_logger.debug('SVGButton: loading %s' % filename)
            self.svg = squirtle.SVG(filename)
        except Exception, e:
            try:
                svgpath = os.path.join(pymt_data_dir, 'icons/svg')
                pymt_logger.exception('SVGButton: unable to load %s' % filename)
                pymt_logger.warning('SVGButton: trying %s' % (
                    svgpath + filename))
                self.svg = squirtle.SVG(os.path.join(svgpath, filename))
            except Exception, e:
                pymt_logger.exception('SVGButton: unable to load file %s' % filename)
示例#21
0
    def _set_filename(self, filename):
        global squirtle
        if squirtle is None:
            import squirtle
# TODO remove this ugly code, improve loader for this
        try:
            pymt_logger.debug('SVGButton: loading %s' % filename)
            self.svg = squirtle.SVG(filename)
        except Exception, e:
            try:
                svgpath = os.path.join(pymt_data_dir, 'icons/svg')
                pymt_logger.exception('SVGButton: unable to load %s' %
                                      filename)
                pymt_logger.warning('SVGButton: trying %s' %
                                    (svgpath + filename))
                self.svg = squirtle.SVG(os.path.join(svgpath, filename))
            except Exception, e:
                pymt_logger.exception('SVGButton: unable to load file %s' %
                                      filename)
示例#22
0
文件: cache.py 项目: triselectif/pymt
    def register(category, limit=None, timeout=None):
        '''Register a new category in cache, with limit

        :Parameters:
            `category` : str
                Identifier of the category
            `limit` : int (optionnal)
                Maximum number of object in the cache.
                If None, no limit is applied.
            `timeout` : double (optionnal)
                Time to delete the object when it's not used.
                if None, no timeout is applied.
        '''
        Cache._categories[category] = {
            'limit': limit,
            'timeout': timeout
        }
        Cache._objects[category] = {}
        pymt_logger.debug('Cache: register <%s> with limit=%s, timeout=%ss' %
            (category, str(limit), str(timeout)))
示例#23
0
    def register(category, limit=None, timeout=None):
        '''Register a new category in cache, with limit

        :Parameters:
            `category` : str
                Identifier of the category
            `limit` : int (optionnal)
                Maximum number of object in the cache.
                If None, no limit is applied.
            `timeout` : double (optionnal)
                Time to delete the object when it's not used.
                if None, no timeout is applied.
        '''
        Cache._categories[category] = {
            'limit': limit,
            'timeout': timeout
        }
        Cache._objects[category] = {}
        pymt_logger.debug('Cache: register <%s> with limit=%s, timeout=%ss' %
            (category, str(limit), str(timeout)))
示例#24
0
文件: svg.py 项目: Markitox/pymt
 def _set_filename(self, filename):
     global squirtle
     if squirtle is None:
         import squirtle
     # TODO remove this ugly code, improve loader for this
     try:
         if self.rawdata is None:
             pymt_logger.debug('SVG: loading %s' % filename)
             self.svg = squirtle.SVG(filename)
         else:
             pymt_logger.debug('SVG: loading %s from rawdata' % filename)
             self.svg = squirtle.SVG(filename=filename, rawdata=self.rawdata)
     except Exception:
         try:
             svgpath = os.path.join(pymt_data_dir, 'icons/svg')
             pymt_logger.exception('SVG: unable to load %s' % filename)
             pymt_logger.warning('SVG: trying %s' % (svgpath + filename))
             self.svg = squirtle.SVG(os.path.join(svgpath, filename))
         except Exception:
             pymt_logger.exception('SVG: unable to load file %s' % filename)
             self._filename = filename
             self.size = (self.svg.width, self.svg.height)
示例#25
0
 def _set_filename(self, filename):
     global squirtle
     if squirtle is None:
         import squirtle
     # TODO remove this ugly code, improve loader for this
     try:
         if self.rawdata is None:
             pymt_logger.debug('SVG: loading %s' % filename)
             self.svg = squirtle.SVG(filename)
         else:
             pymt_logger.debug('SVG: loading %s from rawdata' % filename)
             self.svg = squirtle.SVG(filename=filename,
                                     rawdata=self.rawdata)
     except Exception:
         try:
             svgpath = os.path.join(pymt_data_dir, 'icons/svg')
             pymt_logger.exception('SVG: unable to load %s' % filename)
             pymt_logger.warning('SVG: trying %s' % (svgpath + filename))
             self.svg = squirtle.SVG(os.path.join(svgpath, filename))
         except Exception:
             pymt_logger.exception('SVG: unable to load file %s' % filename)
             self._filename = filename
             self.size = (self.svg.width, self.svg.height)
示例#26
0
 def _set_size(self, size):
     if super(BaseWindow, self)._set_size(size):
         pymt_logger.debug('Window: Resize window to %s' % str(self.size))
         self.dispatch_event('on_resize', *size)
         return True
     return False
示例#27
0
def runTouchApp(widget=None, slave=False):
    '''Static main function that starts the application loop.
    You got some magic things, if you are using argument like this :

    :Parameters:
        `<empty>`
            To make dispatching work, you need at least one
            input listener. If not, application will leave.
            (MTWindow act as an input listener)

        `widget`
            If you pass only a widget, a MTWindow will be created,
            and your widget will be added on the window as the root
            widget.

        `slave`
            No event dispatching are done. This will be your job.

        `widget + slave`
            No event dispatching are done. This will be your job, but
            we are trying to get the window (must be created by you before),
            and add the widget on it. Very usefull for embedding PyMT
            in another toolkit. (like Qt, check pymt-designed)

    '''

    global pymt_evloop

    # Ok, we got one widget, and we are not in slave mode
    # so, user don't create the window, let's create it for him !
    ### Not needed, since we always create window ?!
    #if not slave and widget:
    #    global pymt_window
    #    from ui.window import MTWindow
    #    pymt_window = MTWindow()

    # Instance all configured input
    for key, value in pymt.pymt_config.items('input'):
        pymt_logger.debug('Base: Create provider from %s' % (str(value)))

        # split value
        args = str(value).split(',', 1)
        if len(args) == 1:
            args.append('')
        provider_id, args = args
        provider = TouchFactory.get(provider_id)
        if provider is None:
            pymt_logger.warning('Base: Unknown <%s> provider' % \
                                str(provider_id))
            continue

        # create provider
        p = provider(key, args)
        if p:
            pymt_providers.append(p)

    pymt_evloop = TouchEventLoop()

    # add postproc modules
    for mod in pymt_postproc_modules.values():
        pymt_evloop.add_postproc_module(mod)

    # add main widget
    if widget and getWindow():
        getWindow().add_widget(widget)

    # start event loop
    pymt_logger.info('Base: Start application main loop')
    pymt_evloop.start()

    # we are in a slave mode, don't do dispatching.
    if slave:
        return

    # in non-slave mode, they are 2 issues
    #
    # 1. if user created a window, call the mainloop from window.
    #    This is due to glut, it need to be called with
    #    glutMainLoop(). Only FreeGLUT got a gluMainLoopEvent().
    #    So, we are executing the dispatching function inside
    #    a redisplay event.
    #
    # 2. if no window is created, we are dispatching event lopp
    #    ourself (previous behavior.)
    #
    try:
        if pymt_window is None:
            _run_mainloop()
        else:
            pymt_window.mainloop()
    finally:
        stopTouchApp()
示例#28
0
    pymt_config.adddefaultsection('input')
    pymt_config.adddefaultsection('dump')
    pymt_config.adddefaultsection('modules')
    pymt_config.adddefaultsection('widgets')

    # Upgrade default configuration until having the current version
    need_save = False
    if pymt_config_version != PYMT_CONFIG_VERSION:
        pymt_logger.warning('Config: Older configuration version detected'
                            '(%d instead of %d)' % (
                            pymt_config_version, PYMT_CONFIG_VERSION))
        pymt_logger.warning('Config: Upgrading configuration in progress.')
        need_save = True

    while pymt_config_version < PYMT_CONFIG_VERSION:
        pymt_logger.debug('Config: Upgrading from %d' % pymt_config_version)

        # Versionning introduced in version 0.4.
        if pymt_config_version == 0:

            pymt_config.setdefault('pymt', 'show_fps', '0')
            pymt_config.setdefault('pymt', 'log_level', 'info')
            pymt_config.setdefault('pymt', 'double_tap_time', '250')
            pymt_config.setdefault('pymt', 'double_tap_distance', '20')
            pymt_config.setdefault('pymt', 'enable_simulator', '1')
            pymt_config.setdefault('pymt', 'ignore', '[]')
            pymt_config.setdefault('keyboard', 'layout', 'qwerty')
            pymt_config.setdefault('graphics', 'fbo', 'software')
            pymt_config.setdefault('graphics', 'fullscreen', '0')
            pymt_config.setdefault('graphics', 'width', '640')
            pymt_config.setdefault('graphics', 'height', '480')
示例#29
0
    def create_window(self, params):
        # force display to show (available only for fullscreen)
        displayidx = pymt.pymt_config.getint('graphics', 'display')
        if not 'SDL_VIDEO_FULLSCREEN_HEAD' in os.environ and displayidx != -1:
            os.environ['SDL_VIDEO_FULLSCREEN_HEAD'] = '%d' % displayidx

        # init some opengl, same as before.
        self.flags = pygame.HWSURFACE | pygame.OPENGL | pygame.DOUBLEBUF

        pygame.display.init()

        multisamples = pymt.pymt_config.getint('graphics', 'multisamples')

        if multisamples > 0:
            pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 1)
            pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, multisamples)
        pygame.display.gl_set_attribute(pygame.GL_DEPTH_SIZE, 16)
        pygame.display.gl_set_attribute(pygame.GL_STENCIL_SIZE, 1)
        pygame.display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8)
        pygame.display.set_caption('pymt')

        self._fullscreenmode = params['fullscreen']
        if self._fullscreenmode == 'fake':
            pymt_logger.debug('WinPygame: Set window to fake fullscreen mode')
            self.flags |= pygame.NOFRAME
            os.environ['SDL_VIDEO_WINDOW_POS'] = '0,0'

        elif self._fullscreenmode:
            pymt_logger.debug('WinPygame: Set window to fullscreen mode')
            self.flags |= pygame.FULLSCREEN


        # init ourself size + setmode
        # before calling on_resize
        self._size = params['width'], params['height']
        self._vsync = params['vsync']

        # try to use mode with multisamples
        try:
            self._pygame_set_mode()
        except pygame.error:
            if multisamples:
                pymt_logger.warning('WinPygame: Video: failed (multisamples=%d)' %
                                    multisamples)
                pymt_logger.warning('Video: trying without antialiasing')
                pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 0)
                pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 0)
                multisamples = 0
                self._pygame_set_mode()
            else:
                pymt_logger.warning('WinPygame: Video setup failed :-(')
                raise

        if multisamples:
            try:
                glEnable(GL_MULTISAMPLE_ARB)
            except Exception:
                pass

        super(MTWindowPygame, self).create_window(params)

        # set mouse visibility
        pygame.mouse.set_visible(
            pymt.pymt_config.getboolean('graphics', 'show_cursor'))
示例#30
0
    def _mainloop(self):
        evloop = getEventLoop()
        evloop.idle()

        for event in pygame.event.get():

            # kill application (SIG_TERM)
            if event.type == pygame.QUIT:
                evloop.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_event('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_event(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_event('on_key_up', event.key,
                        event.scancode)
                    continue

                # don't dispatch more key if down event is accepted
                if self.dispatch_event('on_key_down', event.key,
                                       event.scancode, event.unicode):
                    continue
                self.dispatch_event('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:
                pymt_logger.debug('WinPygame: Unhandled event %s' % str(event))
示例#31
0
文件: base.py 项目: OpenWerkplek/pymt
def runTouchApp(widget=None, slave=False):
    '''Static main function that starts the application loop.
    You got some magic things, if you are using argument like this :

    :Parameters:
        `<empty>`
            To make dispatching work, you need at least one
            input listener. If not, application will leave.
            (MTWindow act as an input listener)

        `widget`
            If you pass only a widget, a MTWindow will be created,
            and your widget will be added on the window as the root
            widget.

        `slave`
            No event dispatching are done. This will be your job.

        `widget + slave`
            No event dispatching are done. This will be your job, but
            we are trying to get the window (must be created by you before),
            and add the widget on it. Very usefull for embedding PyMT
            in another toolkit. (like Qt, check pymt-designed)

    '''

    global pymt_evloop

    # Ok, we got one widget, and we are not in slave mode
    # so, user don't create the window, let's create it for him !
    ### Not needed, since we always create window ?!
    #if not slave and widget:
    #    global pymt_window
    #    from ui.window import MTWindow
    #    pymt_window = MTWindow()

    # Instance all configured input
    for key, value in pymt.pymt_config.items('input'):
        pymt_logger.debug('Base: Create provider from %s' % (str(value)))

        # split value
        args = str(value).split(',', 1)
        if len(args) == 1:
            args.append('')
        provider_id, args = args
        provider = TouchFactory.get(provider_id)
        if provider is None:
            pymt_logger.warning('Base: Unknown <%s> provider' % \
                                str(provider_id))
            continue

        # create provider
        p = provider(key, args)
        if p:
            pymt_providers.append(p)

    pymt_evloop = TouchEventLoop()

    # add postproc modules
    for mod in pymt_postproc_modules.values():
        pymt_evloop.add_postproc_module(mod)

    # add main widget
    if widget and getWindow():
        getWindow().add_widget(widget)

    # start event loop
    pymt_logger.info('Base: Start application main loop')
    pymt_evloop.start()

    # we are in a slave mode, don't do dispatching.
    if slave:
        return

    # in non-slave mode, they are 2 issues
    #
    # 1. if user created a window, call the mainloop from window.
    #    This is due to glut, it need to be called with
    #    glutMainLoop(). Only FreeGLUT got a gluMainLoopEvent().
    #    So, we are executing the dispatching function inside
    #    a redisplay event.
    #
    # 2. if no window is created, we are dispatching event lopp
    #    ourself (previous behavior.)
    #
    try:
        if pymt_window is None:
            _run_mainloop()
        else:
            pymt_window.mainloop()
    finally:
        stopTouchApp()
示例#32
0
    def create_window(self, params):
        # force display to show (available only for fullscreen)
        displayidx = pymt.pymt_config.getint('graphics', 'display')
        if not 'SDL_VIDEO_FULLSCREEN_HEAD' in os.environ and displayidx != -1:
            os.environ['SDL_VIDEO_FULLSCREEN_HEAD'] = '%d' % displayidx

        # init some opengl, same as before.
        self.flags = pygame.HWSURFACE | pygame.OPENGL | pygame.DOUBLEBUF

        pygame.display.init()

        multisamples = pymt.pymt_config.getint('graphics', 'multisamples')

        if multisamples > 0:
            pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 1)
            pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES,
                                            multisamples)
        pygame.display.gl_set_attribute(pygame.GL_DEPTH_SIZE, 16)
        pygame.display.gl_set_attribute(pygame.GL_STENCIL_SIZE, 1)
        pygame.display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8)
        pygame.display.set_caption('pymt')

        if params['position'] == 'auto':
            self._pos = None
        elif params['position'] == 'custom':
            self._pos = params['left'], params['top']
        else:
            raise ValueError('position token in configuration accept only '
                             '"auto" or "custom"')

        self._fullscreenmode = params['fullscreen']
        if self._fullscreenmode == 'fake':
            pymt_logger.debug('WinPygame: Set window to fake fullscreen mode')
            self.flags |= pygame.NOFRAME
            # if no position set, in fake mode, we always need to set the
            # position. so replace 0, 0.
            if self._pos is None:
                self._pos = (0, 0)
            os.environ['SDL_VIDEO_WINDOW_POS'] = '%d,%d' % self._pos

        elif self._fullscreenmode:
            pymt_logger.debug('WinPygame: Set window to fullscreen mode')
            self.flags |= pygame.FULLSCREEN

        elif self._pos is not None:
            os.environ['SDL_VIDEO_WINDOW_POS'] = '%d,%d' % self._pos

        # never stay with a None pos, application using w.center will be fired.
        self._pos = (0, 0)

        # prepare keyboard
        repeat_delay = int(pymt.pymt_config.get('keyboard', 'repeat_delay'))
        repeat_rate = float(pymt.pymt_config.get('keyboard', 'repeat_rate'))
        pygame.key.set_repeat(repeat_delay, int(1000. / repeat_rate))

        # set window icon before calling set_mode
        icon = pygame.image.load(
            pymt.pymt_config.get('graphics', 'window_icon'))
        pygame.display.set_icon(icon)

        # init ourself size + setmode
        # before calling on_resize
        self._size = params['width'], params['height']
        self._vsync = params['vsync']
        self._fps = float(params['fps'])

        # ensure the default fps will be 60 if vsync is actived
        # and if user didn't set any maximum fps.
        if self._vsync and self._fps <= 0:
            self._fps = 60.

        # try to use mode with multisamples
        try:
            self._pygame_set_mode()
        except pygame.error:
            if multisamples:
                pymt_logger.warning(
                    'WinPygame: Video: failed (multisamples=%d)' %
                    multisamples)
                pymt_logger.warning('Video: trying without antialiasing')
                pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS,
                                                0)
                pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES,
                                                0)
                multisamples = 0
                self._pygame_set_mode()
            else:
                pymt_logger.warning('WinPygame: Video setup failed :-(')
                raise

        if multisamples:
            try:
                glEnable(GL_MULTISAMPLE_ARB)
            except Exception:
                pass

        super(MTWindowPygame, self).create_window(params)

        # set mouse visibility
        pygame.mouse.set_visible(
            pymt.pymt_config.getboolean('graphics', 'show_cursor'))

        # set rotation
        self.rotation = params['rotation']
示例#33
0
文件: config.py 项目: gavine199/pymt
    pymt_config.adddefaultsection('input')
    pymt_config.adddefaultsection('dump')
    pymt_config.adddefaultsection('modules')
    pymt_config.adddefaultsection('widgets')

    # Upgrade default configuration until having the current version
    need_save = False
    if pymt_config_version != PYMT_CONFIG_VERSION:
        pymt_logger.warning('Config: Older configuration version detected'
                            '(%d instead of %d)' % (
                            pymt_config_version, PYMT_CONFIG_VERSION))
        pymt_logger.warning('Config: Upgrading configuration in progress.')
        need_save = True

    while pymt_config_version < PYMT_CONFIG_VERSION:
        pymt_logger.debug('Config: Upgrading from %d' % pymt_config_version)

        # Versionning introduced in version 0.4.
        if pymt_config_version == 0:

            pymt_config.setdefault('pymt', 'show_fps', '0')
            pymt_config.setdefault('pymt', 'log_level', 'info')
            pymt_config.setdefault('pymt', 'double_tap_time', '250')
            pymt_config.setdefault('pymt', 'double_tap_distance', '20')
            pymt_config.setdefault('pymt', 'enable_simulator', '1')
            pymt_config.setdefault('pymt', 'ignore', '[]')
            pymt_config.setdefault('keyboard', 'layout', 'qwerty')
            pymt_config.setdefault('graphics', 'fbo', 'hardware')
            pymt_config.setdefault('graphics', 'fullscreen', '0')
            pymt_config.setdefault('graphics', 'width', '640')
            pymt_config.setdefault('graphics', 'height', '480')
示例#34
0
 def register(classobj):
     '''Register a new class to load sound'''
     pymt_logger.debug('Audio: register %s' % classobj.__name__)
     SoundLoader._classes.append(classobj)
示例#35
0
            elif opt in ('-s', '--save'):
                need_save = True
            elif opt in ('-n', ):
                pymt_options['shadow_window'] = False

        if need_save:
            try:
                with open(pymt_config_fn, 'w') as fd:
                    pymt_config.write(fd)
            except Exception, e:
                pymt_logger.exception('Core: error while saving default'
                                      'configuration file')
            pymt_logger.info('Core: PyMT configuration saved.')
            sys.exit(0)

        # last initialization
        if pymt_options['shadow_window']:
            pymt_logger.debug('Core: Creating PyMT Window')
            shadow_window = MTWindow()
            pymt_configure()

    except getopt.GetoptError, err:
        pymt_logger.error('Core: %s' % str(err))
        pymt_usage()
        sys.exit(2)

# cleanup namespace
if not 'PYMT_DOC_INCLUDE' in os.environ:
    del level, need_save, opts, args
del sys, getopt, os, key
示例#36
0
文件: __init__.py 项目: boothead/pymt
        set_color(*self.touch_color)
        for touch in getCurrentTouches():
            drawCircle(pos=(touch.x, touch.y), radius=self.radius)


# Searching the best provider
MTWindow = None
if not "PYMT_DOC" in os.environ:
    if "pygame" in pymt.pymt_options["window"]:
        try:
            import win_pygame

            MTWindow = win_pygame.MTWindowPygame
            pymt_logger.info("Window: use Pygame as window provider.")
        except ImportError:
            pymt_logger.debug("Window: Unable to use Pygame as provider.")

    if MTWindow is None and "glut" in pymt.pymt_options["window"]:
        try:
            import win_glut

            MTWindow = win_glut.MTWindowGlut
            pymt_logger.info("Window: use GLUT as window provider.")
        except ImportError:
            pymt_logger.debug("Window: Unable to use GLUT as provider.")

    # No window provider ?
    if MTWindow is None:
        pymt_logger.critical("Window: No provider found (configuration is %s)" % str(pymt.pymt_options["window"]))

# Register all base widgets
示例#37
0
文件: __init__.py 项目: Markitox/pymt
 def register(classobj):
     '''Register a new class to load sound'''
     pymt_logger.debug('Audio: register %s' % classobj.__name__)
     SoundLoader._classes.append(classobj)
示例#38
0
            elif opt in ('-r', '--rotation'):
                pymt_config.set('graphics', 'rotation', arg)
            elif opt in ('-n', ):
                pymt_options['shadow_window'] = False

        if need_save:
            try:
                with open(pymt_config_fn, 'w') as fd:
                    pymt_config.write(fd)
            except Exception, e:
                pymt_logger.exception('Core: error while saving default'
                                      'configuration file')
            pymt_logger.info('Core: PyMT configuration saved.')
            sys.exit(0)

        # last initialization
        if pymt_options['shadow_window']:
            pymt_logger.debug('Core: Creating PyMT Window')
            shadow_window = MTWindow()
            pymt_configure()

    except getopt.GetoptError, err:
        pymt_logger.error('Core: %s' % str(err))
        pymt_usage()
        sys.exit(2)

# cleanup namespace
if not 'PYMT_DOC_INCLUDE' in os.environ:
    del level, need_save, opts, args
del sys, getopt, os, key
示例#39
0
    def create_window(self, params):
        # force display to show (available only for fullscreen)
        displayidx = pymt.pymt_config.getint('graphics', 'display')
        if not 'SDL_VIDEO_FULLSCREEN_HEAD' in os.environ and displayidx != -1:
            os.environ['SDL_VIDEO_FULLSCREEN_HEAD'] = '%d' % displayidx

        # init some opengl, same as before.
        self.flags = pygame.HWSURFACE | pygame.OPENGL | pygame.DOUBLEBUF

        pygame.display.init()

        multisamples = pymt.pymt_config.getint('graphics', 'multisamples')

        if multisamples > 0:
            pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 1)
            pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, multisamples)
        pygame.display.gl_set_attribute(pygame.GL_DEPTH_SIZE, 16)
        pygame.display.gl_set_attribute(pygame.GL_STENCIL_SIZE, 1)
        pygame.display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8)
        pygame.display.set_caption('pymt')

        if params['position'] == 'auto':
            self._pos = None
        elif params['position'] == 'custom':
            self._pos = params['left'], params['top']
        else:
            raise ValueError('position token in configuration accept only '
                             '"auto" or "custom"')

        self._fullscreenmode = params['fullscreen']
        if self._fullscreenmode == 'fake':
            pymt_logger.debug('WinPygame: Set window to fake fullscreen mode')
            self.flags |= pygame.NOFRAME
            # if no position set, in fake mode, we always need to set the
            # position. so replace 0, 0.
            if self._pos is None:
                self._pos = (0, 0)
            os.environ['SDL_VIDEO_WINDOW_POS'] = '%d,%d' % self._pos

        elif self._fullscreenmode:
            pymt_logger.debug('WinPygame: Set window to fullscreen mode')
            self.flags |= pygame.FULLSCREEN

        elif self._pos is not None:
            os.environ['SDL_VIDEO_WINDOW_POS'] = '%d,%d' % self._pos

        # never stay with a None pos, application using w.center will be fired.
        self._pos = (0, 0)

        # prepare keyboard
        repeat_delay = int(pymt.pymt_config.get('keyboard', 'repeat_delay'))
        repeat_rate = float(pymt.pymt_config.get('keyboard', 'repeat_rate'))
        pygame.key.set_repeat(repeat_delay, int(1000. / repeat_rate))

        # set window icon before calling set_mode
        icon = pygame.image.load(pymt.pymt_config.get('graphics', 'window_icon'))
        pygame.display.set_icon(icon)

        # init ourself size + setmode
        # before calling on_resize
        self._size = params['width'], params['height']
        self._vsync = params['vsync']
        self._fps = float(params['fps'])

        # ensure the default fps will be 60 if vsync is actived
        # and if user didn't set any maximum fps.
        if self._vsync and self._fps <= 0:
            self._fps = 60.

        # try to use mode with multisamples
        try:
            self._pygame_set_mode()
        except pygame.error:
            if multisamples:
                pymt_logger.warning('WinPygame: Video: failed (multisamples=%d)' %
                                    multisamples)
                pymt_logger.warning('Video: trying without antialiasing')
                pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 0)
                pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 0)
                multisamples = 0
                self._pygame_set_mode()
            else:
                pymt_logger.warning('WinPygame: Video setup failed :-(')
                raise

        if multisamples:
            try:
                glEnable(GL_MULTISAMPLE_ARB)
            except Exception:
                pass

        super(MTWindowPygame, self).create_window(params)

        # set mouse visibility
        pygame.mouse.set_visible(
            pymt.pymt_config.getboolean('graphics', 'show_cursor'))

        # set rotation
        self.rotation = params['rotation']
示例#40
0
文件: __init__.py 项目: boothead/pymt
 def _set_size(self, size):
     if super(BaseWindow, self)._set_size(size):
         pymt_logger.debug("Window: Resize window to %s" % str(self.size))
         self.dispatch_event("on_resize", *size)
         return True
     return False
示例#41
0
        '''Draw a circle under every touches'''
        set_color(*self.touch_color)
        for touch in getCurrentTouches():
            drawCircle(pos=(touch.x, touch.y), radius=self.radius)


# Searching the best provider
MTWindow = None
if not 'PYMT_DOC' in os.environ:
    if 'pygame' in pymt.pymt_options['window']:
        try:
            import win_pygame
            MTWindow = win_pygame.MTWindowPygame
            pymt_logger.info('Window: use Pygame as window provider.')
        except ImportError:
            pymt_logger.debug('Window: Unable to use Pygame as provider.')

    if MTWindow is None and 'glut' in pymt.pymt_options['window']:
        try:
            import win_glut
            MTWindow = win_glut.MTWindowGlut
            pymt_logger.info('Window: use GLUT as window provider.')
        except ImportError:
            pymt_logger.debug('Window: Unable to use GLUT as provider.')

    # No window provider ?
    if MTWindow is None:
        pymt_logger.critical(
            'Window: No provider found (configuration is %s)' %
            str(pymt.pymt_options['window']))