Пример #1
1
    def __init__(self, **kwargs):
        # XXX move to style.kv
        if 'size_hint' not in kwargs:
            if 'size_hint_x' not in kwargs:
                self.size_hint_x = None
            if 'size_hint_y' not in kwargs:
                self.size_hint_y = None
        if 'size' not in kwargs:
            if 'width' not in kwargs:
                self.width = 700
            if 'height' not in kwargs:
                self.height = 200
        if 'scale_min' not in kwargs:
            self.scale_min = .4
        if 'scale_max' not in kwargs:
            self.scale_max = 1.6
        if 'docked' not in kwargs:
            self.docked = False

        layout_mode = self._trigger_update_layout_mode = Clock.create_trigger(
            self._update_layout_mode)
        layouts = self._trigger_load_layouts = Clock.create_trigger(
            self._load_layouts)
        layout = self._trigger_load_layout = Clock.create_trigger(
            self._load_layout)
        fbind = self.fbind

        fbind('docked', self.setup_mode)
        fbind('have_shift', layout_mode)
        fbind('have_capslock', layout_mode)
        fbind('have_special', layout_mode)
        fbind('layout_path', layouts)
        fbind('layout', layout)
        super(VKeyboard, self).__init__(**kwargs)

        # load all the layouts found in the layout_path directory
        self._load_layouts()

        # ensure we have default layouts
        available_layouts = self.available_layouts
        if not available_layouts:
            Logger.critical('VKeyboard: unable to load default layouts')

        # load the default layout from configuration
        if self.layout is None:
            self.layout = Config.get('kivy', 'keyboard_layout')
        else:
            # ensure the current layout is found on the available layout
            self._trigger_load_layout()

        # update layout mode (shift or normal)
        self._trigger_update_layout_mode()

        # create a top layer to draw active keys on
        with self.canvas:
            self.background_key_layer = Canvas()
            self.active_keys_layer = Canvas()
Пример #2
0
    def _configure(self):
        from time import strftime
        from kivy.config import Config

        log_dir = Config.get("kivy", "log_dir")
        log_name = Config.get("kivy", "log_name")

        _dir = kivy.kivy_home_dir
        if len(log_dir) and log_dir[0] == "/":
            _dir = log_dir
        else:
            _dir = os.path.join(_dir, log_dir)
            if not os.path.exists(_dir):
                os.mkdir(_dir)

        self.purge_logs(_dir)

        pattern = log_name.replace("%_", "@@NUMBER@@")
        pattern = os.path.join(_dir, strftime(pattern))
        n = 0
        while True:
            filename = pattern.replace("@@NUMBER@@", str(n))
            if not os.path.exists(filename):
                break
            n += 1
            if n > 10000:  # prevent maybe flooding ?
                raise Exception("Too many logfile, remove them")

        FileHandler.filename = filename
        FileHandler.fd = open(filename, "w")

        Logger.info("Logger: Record log in %s" % filename)
Пример #3
0
    def build(self):
        config = self.config

        # Input
        if config.getboolean("input", "tuio"):
            try:
                KivyConfig.get("input", "tuiotouchscreen")
            except (NoSectionError, NoOptionError):
                KivyConfig.set('input', 'tuiotouchscreen', 'tuio,0.0.0.0:3333')
                KivyConfig.write()
        if config.getboolean("input", "touch"):
            # Enable mouse interface
            kv_filename = 'gameoflife-nontuio.kv'
        else:
            kv_filename = 'gameoflife-tuio.kv'

        # Game
        self.speed = config.getint("game", "speed")
        self.iterations_per_turn = config.getint("game", "iterations_per_turn")
        self.top_score = config.getint("game", "top_score")
        self.minimum_pieces = config.getint("game", "minimum_pieces")

        # Root widget
        self.root = Builder.load_file(kv_filename)
        self.root.app = self

        # Grid
        self.root.grid.rows = config.getint("grid", "rows")
        self.root.grid.cols = config.getint("grid", "cols")
        self.root.grid.cell_size = config.getint("grid", "cell_size")
Пример #4
0
    def _configure(self, *largs, **kwargs):
        from time import strftime
        from kivy.config import Config
        log_dir = Config.get('kivy', 'log_dir')
        log_name = Config.get('kivy', 'log_name')

        _dir = kivy.kivy_home_dir
        if log_dir and os.path.isabs(log_dir):
            _dir = log_dir
        else:
            _dir = os.path.join(_dir, log_dir)
        if not os.path.exists(_dir):
            os.makedirs(_dir)

        self.purge_logs(_dir)

        pattern = log_name.replace('%_', '@@NUMBER@@')
        pattern = os.path.join(_dir, strftime(pattern))
        n = 0
        while True:
            filename = pattern.replace('@@NUMBER@@', str(n))
            if not os.path.exists(filename):
                break
            n += 1
            if n > 10000:  # prevent maybe flooding ?
                raise Exception('Too many logfile, remove them')

        if FileHandler.filename == filename and FileHandler.fd is not None:
            return
        FileHandler.filename = filename
        if FileHandler.fd is not None:
            FileHandler.fd.close()
        FileHandler.fd = open(filename, 'w')

        Logger.info('Logger: Record log in %s' % filename)
Пример #5
0
    def _configure_module(self, name):
        if 'module' not in self.mods[name]:
            try:
                self.import_module(name)
            except ImportError:
                return

        # convert configuration like:
        # -m mjpegserver:port=8080,fps=8
        # and pass it in context.config token
        config = dict()

        args = Config.get('modules', name)
        if args != '':
            values = Config.get('modules', name).split(',')
            for value in values:
                x = value.split('=', 1)
                if len(x) == 1:
                    config[x[0]] = True
                else:
                    config[x[0]] = x[1]

        self.mods[name]['context'].config = config

        # call configure if module have one
        if hasattr(self.mods[name]['module'], 'configure'):
            self.mods[name]['module'].configure(config)
Пример #6
0
    def _configure(self):
        from time import strftime
        from kivy.config import Config
        log_dir = Config.get('kivy', 'log_dir')
        log_name = Config.get('kivy', 'log_name')

        _dir = kivy.kivy_home_dir
        if len(log_dir) and log_dir[0] == '/':
            _dir = log_dir
        else:
            _dir = os.path.join(_dir, log_dir)
            if not os.path.exists(_dir):
                os.mkdir(_dir)

        self.purge_logs(_dir)

        pattern = log_name.replace('%_', '@@NUMBER@@')
        pattern = os.path.join(_dir, strftime(pattern))
        n = 0
        while True:
            filename = pattern.replace('@@NUMBER@@', str(n))
            if not os.path.exists(filename):
                break
            n += 1
            if n > 10000: # prevent maybe flooding ?
                raise Exception('Too many logfile, remove them')

        FileHandler.filename = filename
        FileHandler.fd = open(filename, 'w')

        Logger.info('Logger: Record log in %s' % filename)
Пример #7
0
    def activate_module(self, name, win):
        '''Activate a module on a window'''
        if not name in self.mods:
            Logger.warning('Modules: Module <%s> not found' % name)
            return

        if not 'module' in self.mods[name]:
            try:
                self.import_module(name)
            except ImportError:
                return

        module = self.mods[name]['module']
        if not self.mods[name]['activated']:

            # convert configuration like:
            # -m mjpegserver:port=8080,fps=8
            # and pass it in context.config token
            config = dict()

            args = Config.get('modules', name)
            if args != '':
                values = Config.get('modules', name).split(',')
                for value in values:
                    x = value.split('=', 1)
                    if len(x) == 1:
                        config[x[0]] = True
                    else:
                        config[x[0]] = x[1]

            msg = 'Modules: Start <%s> with config %s' % (name, str(config))
            Logger.debug(msg)
            self.mods[name]['context'].config = config
            module.start(win, self.mods[name]['context'])
Пример #8
0
    def _configure_module(self, name):
        if "module" not in self.mods[name]:
            try:
                self.import_module(name)
            except ImportError:
                return

        # convert configuration like:
        # -m mjpegserver:port=8080,fps=8
        # and pass it in context.config token
        config = dict()

        args = Config.get("modules", name)
        if args != "":
            values = Config.get("modules", name).split(",")
            for value in values:
                x = value.split("=", 1)
                if len(x) == 1:
                    config[x[0]] = True
                else:
                    config[x[0]] = x[1]

        self.mods[name]["context"].config = config

        # call configure if module have one
        if hasattr(self.mods[name]["module"], "configure"):
            self.mods[name]["module"].configure(config)
Пример #9
0
 def build(self):
     #Set window's size
     print(Config.get('graphics', 'width'))
     print(Config.get('graphics', 'height'))
     #Start the game
     game = Game3()
     Clock.schedule_interval(game.update, 1.0 / 60.0)
     Clock.schedule_interval(game.increment_clock, 1.0)
     return game
Пример #10
0
    def __init__(self, **kwargs):
        super(KeyboardTest, self).__init__(**kwargs)
        #self._add_numeric()  # Please see below
        self._add_keyboards()
        self._keyboard = None

        #TODO: Remove or document?
        Logger.info("main.py: keyboard_mode=" +
                    Config.get("kivy", "keyboard_mode"))
        Config.set("kivy", "keyboard_mode", "dock")
        Config.write()
        Logger.info("main.py: 2. keyboard_mode=" +
                    Config.get("kivy", "keyboard_mode"))
Пример #11
0
    def configure_keyboards(self):
        # Configure how to provide keyboards (virtual or not)

        # register system keyboard to listening keys from window
        sk = self._system_keyboard
        self.bind(
            on_key_down=sk._on_window_key_down,
            on_key_up=sk._on_window_key_up,
            on_textinput=sk._on_window_textinput)

        # use the device's real keyboard
        self.use_syskeyboard = True

        # use the device's real keyboard
        self.allow_vkeyboard = False

        # one single vkeyboard shared between all widgets
        self.single_vkeyboard = True

        # the single vkeyboard is always sitting at the same position
        self.docked_vkeyboard = False

        # now read the configuration
        mode = Config.get('kivy', 'keyboard_mode')
        if mode not in ('', 'system', 'dock', 'multi', 'systemanddock',
                        'systemandmulti'):
            Logger.critical('Window: unknown keyboard mode %r' % mode)

        # adapt mode according to the configuration
        if mode == 'system':
            self.use_syskeyboard = True
            self.allow_vkeyboard = False
            self.single_vkeyboard = True
            self.docked_vkeyboard = False
        elif mode == 'dock':
            self.use_syskeyboard = False
            self.allow_vkeyboard = True
            self.single_vkeyboard = True
            self.docked_vkeyboard = True
        elif mode == 'multi':
            self.use_syskeyboard = False
            self.allow_vkeyboard = True
            self.single_vkeyboard = False
            self.docked_vkeyboard = False
        elif mode == 'systemanddock':
            self.use_syskeyboard = True
            self.allow_vkeyboard = True
            self.single_vkeyboard = True
            self.docked_vkeyboard = True
        elif mode == 'systemandmulti':
            self.use_syskeyboard = True
            self.allow_vkeyboard = True
            self.single_vkeyboard = False
            self.docked_vkeyboard = False

        Logger.info(
            'Window: virtual keyboard %sallowed, %s, %s' % (
                '' if self.allow_vkeyboard else 'not ',
                'single mode' if self.single_vkeyboard else 'multiuser mode',
                'docked' if self.docked_vkeyboard else 'not docked'))
Пример #12
0
    def _set_shape(self, shape_image, mode='default',
                   cutoff=False, color_key=None):
        modes = ('default', 'binalpha', 'reversebinalpha', 'colorkey')
        color_key = color_key or (0, 0, 0, 1)
        if mode not in modes:
            Logger.warning(
                'Window: shape mode can be only '
                '{}'.format(', '.join(modes))
            )
            return
        if not isinstance(color_key, (tuple, list)):
            return
        if len(color_key) not in (3, 4):
            return
        if len(color_key) == 3:
            color_key = (color_key[0], color_key[1], color_key[2], 1)
            Logger.warning(
                'Window: Shape color_key must be only tuple or list'
            )
            return
        color_key = (
            color_key[0] * 255,
            color_key[1] * 255,
            color_key[2] * 255,
            color_key[3] * 255
        )

        assert cutoff in (1, 0)
        shape_image = shape_image or Config.get('kivy', 'window_shape')
        shape_image = resource_find(shape_image) or shape_image
        self._win.set_shape(shape_image, mode, cutoff, color_key)
Пример #13
0
    def run(self):
        q = self._queue.appendleft
        url = self.url
        req_body = self.req_body
        req_headers = self.req_headers or {}
        if (
            Config.has_section('network')
            and 'useragent' in Config.items('network')
        ):
            useragent = Config.get('network', 'useragent')
            req_headers.setdefault('User-Agent', useragent)

        try:
            result, resp = self._fetch_url(url, req_body, req_headers, q)
            if self.decode:
                result = self.decode_result(result, resp)
        except Exception as e:
            q(('error', None, e))
        else:
            q(('success', resp, result))

        # using trigger can result in a missed on_success event
        self._trigger_result()

        # clean ourself when the queue is empty
        while len(self._queue):
            sleep(.1)
            self._trigger_result()

        # ok, authorize the GC to clean us.
        if self in g_requests:
            g_requests.remove(self)
Пример #14
0
 def __init__(self, **kwargs):
     self._win = None
     if 'min_state_time' not in kwargs:
         self.min_state_time = float(
             Config.get('graphics', 'min_state_time'))
     if 'container' not in kwargs:
         c = self.container = Builder.load_string(_grid_kv)
     else:
         c = None
     if 'allow_sides' not in kwargs:
         self.allow_sides = False
     if 'do_scroll_x' not in kwargs:
         self.do_scroll_x = False
     if 'size_hint' not in kwargs:
         if 'size_hint_x' not in kwargs:
             self.size_hint_x = None
         if 'size_hint_y' not in kwargs:
             self.size_hint_y = None
     super(DropDown, self).__init__(**kwargs)
     if c is not None:
         super(DropDown, self).add_widget(c)
         self.on_container(self, c)
     Window.bind(
         on_key_down=self.on_key_down,
         size=self._reposition)
     self.fbind('size', self._reposition)
Пример #15
0
    def build(self):
        #init config
        self.desktop = bool(Config.get('kivy', 'desktop'))
        #init gui
        self.mainform = RootLayout()
        #init logger
        self.mainform.logstream = self.mainform.console_log.initstream()
        self.mainform.logstreamhandler = logging.StreamHandler(self.mainform.logstream)
        self.mainform.logstreamhandler.setFormatter(logging.Formatter("%(asctime)s.%(msecs)d [%(name)s#%(levelname)s]: %(message)s","%H:%M:%S"))
        self.mainform.logstreamhandler.setLevel(logging.INFO)
        self.mainform.consoleloghandler = logging.StreamHandler(sys.stdout)
        self.mainform.consoleloghandler.setFormatter(logging.Formatter("%(asctime)s [%(name)s#%(levelname)s]: %(message)s"))
        self.mainform.consoleloghandler.setLevel(logging.DEBUG)
        self.mainform.log = logging.getLogger('Pilot')
        self.mainform.log.setLevel(logging.DEBUG)
        self.mainform.log.addHandler(self.mainform.logstreamhandler)
        self.mainform.log.addHandler(self.mainform.consoleloghandler)
        self.mainform.log.info (u"kPilotGui Running on Python " + sys.version)
        #init backend
        pilot.init(self.mainform.log)
        #delayed init for backend-dependent construction
        self.mainform.delayed_init()

        #init sheduler
        Clock.schedule_interval(self.mainform.logupdate, .1)
#        Clock.schedule_interval(pilot.udpreader, .05)
        

        return self.mainform
Пример #16
0
    def configure_keyboards(self):
        # Configure how to provide keyboards (virtual or not)

        # register system keyboard to listening keys from window
        sk = self._system_keyboard
        self.bind(on_key_down=sk._on_window_key_down, on_key_up=sk._on_window_key_up)

        # use the device's real keyboard
        self.use_syskeyboard = True

        # use the device's real keyboard
        self.allow_vkeyboard = False

        # one single vkeyboard shared between all widgets
        self.single_vkeyboard = True

        # the single vkeyboard is always sitting at the same position
        self.docked_vkeyboard = False

        # now read the configuration
        mode = Config.get("kivy", "keyboard_mode")
        if mode not in ("", "system", "dock", "multi", "systemanddock", "systemandmulti"):
            Logger.critical("Window: unknown keyboard mode %r" % mode)

        # adapt mode according to the configuration
        if mode == "system":
            self.use_syskeyboard = True
            self.allow_vkeyboard = False
            self.single_vkeyboard = True
            self.docked_vkeyboard = False
        elif mode == "dock":
            self.use_syskeyboard = False
            self.allow_vkeyboard = True
            self.single_vkeyboard = True
            self.docked_vkeyboard = True
        elif mode == "multi":
            self.use_syskeyboard = False
            self.allow_vkeyboard = True
            self.single_vkeyboard = False
            self.docked_vkeyboard = False
        elif mode == "systemanddock":
            self.use_syskeyboard = True
            self.allow_vkeyboard = True
            self.single_vkeyboard = True
            self.docked_vkeyboard = True
        elif mode == "systemandmulti":
            self.use_syskeyboard = True
            self.allow_vkeyboard = True
            self.single_vkeyboard = False
            self.docked_vkeyboard = False

        Logger.info(
            "Window: virtual keyboard %sallowed, %s, %s"
            % (
                "" if self.allow_vkeyboard else "not ",
                "single mode" if self.single_vkeyboard else "multiuser mode",
                "docked" if self.docked_vkeyboard else "not docked",
            )
        )
Пример #17
0
    def create_window(self, *largs):

        if self._fake_fullscreen:
            if not self.borderless:
                self.fullscreen = self._fake_fullscreen = False
            elif not self.fullscreen or self.fullscreen == 'auto':
                self.borderless = self._fake_fullscreen = False

        if self.fullscreen == 'fake':
            self.borderless = self._fake_fullscreen = True
            Logger.warning("The 'fake' fullscreen option has been "
                            "deprecated, use Window.borderless or the "
                            "borderless Config option instead.")

        if not self.initialized:

            if self.position == 'auto':
                pos = None, None
            elif self.position == 'custom':
                pos = self.left, self.top

            # setup !
            w, h = self._size
            resizable = Config.getboolean('graphics', 'resizable')
            gl_size = self._win.setup_window(pos[0], pos[1], w, h,
                                             self.borderless, self.fullscreen,
                                             resizable)
            # never stay with a None pos, application using w.center
            # will be fired.
            self._pos = (0, 0)
        else:
            w, h = self._size
            self._win.resize_window(w, h)
            self._win.set_border_state(self.borderless)
            self._win.set_fullscreen_mode(self.fullscreen)

        super(WindowSDL, self).create_window()

        # auto add input provider
        Logger.info('Window: auto add sdl input provider')
        from kivy.base import EventLoop
        SDL2MotionEventProvider.win = self
        EventLoop.add_input_provider(SDL2MotionEventProvider('sdl', ''))

        # set window icon before calling set_mode
        try:
            filename_icon = self.icon or Config.get('kivy', 'window_icon')
            if filename_icon == '':
                logo_size = 32
                if platform == 'macosx':
                    logo_size = 512
                elif platform == 'win':
                    logo_size = 64
                filename_icon = 'kivy-icon-{}.png'.format(logo_size)
                filename_icon = resource_find(
                        join(kivy_data_dir, 'logo', filename_icon))
            self.set_icon(filename_icon)
        except:
            Logger.exception('Window: cannot set icon')
Пример #18
0
 def __init__(self, **kwargs):
     self.register_event_type('on_press')
     self.register_event_type('on_release')
     if 'min_state_time' not in kwargs:
         self.min_state_time = float(Config.get('graphics', 'min_state_time'))
     super(ButtonBehavior, self).__init__(**kwargs)
     self.__state_event = None
     self.__touch_time = None
     self.fbind('state', self.cancel_event)
Пример #19
0
    def __init__(self, freq, verbose=False):
        Config.adddefaultsection('debug')
        Config.setdefault('debug', 'timeit', '0')

        if int(Config.get('debug', 'timeit')) == 0:
            self.freq = 0
        else:
            self.freq = freq
            self.ncalls = 0
            self.verbose = verbose
    def __init__(self, **kwargs):
        self.dwell_color = [eval(n) for n in Config.get('dwell', 'dwell_color').split(',')]
        self.dwell_width = Config.getfloat('dwell', 'dwell_width')
        self.dwell_time  = Config.getfloat('dwell', 'dwell_time')
        self.dwell_jitter_distance_ignore = Config.getfloat('dwell', 'dwell_jitter_distance_ignore')
        self.dwell_initial_wait_period  = Config.getfloat('dwell', 'dwell_initial_wait_period')

        # Add-on hack at the last moment, need the touch info from the dwell
        self.dwell_touch = None
        self.double_tap_touch = None

        super(DwellBase, self).__init__(**kwargs)
Пример #21
0
    def __init__(self):
        ret = super(Game, self).__init__()
        Config.adddefaultsection('records')
        Config.setdefault('records', 'top_points', '0')

        self.sounds = dict()
        self.sounds['firing'] = SoundLoader.load("sounds/firing.ogg")
        self.sounds['enemy_death'] = SoundLoader.load("sounds/enemy_death.ogg")
        self.sounds['game_over'] = SoundLoader.load("sounds/game_over.ogg")
        self.top_points = int(Config.get('records', 'top_points'))
        self.points = 0
        self.reset_state()
        return ret
Пример #22
0
    def __init__(self, **kwargs):
        # XXX move to style.kv
        kwargs.setdefault('size_hint', (None, None))
        kwargs.setdefault('scale_min', .4)
        kwargs.setdefault('scale_max', 1.6)
        kwargs.setdefault('size', (700, 200))
        kwargs.setdefault('docked', False)
        self._trigger_update_layout_mode = Clock.create_trigger(
            self._update_layout_mode)
        self._trigger_load_layouts = Clock.create_trigger(
            self._load_layouts)
        self._trigger_load_layout = Clock.create_trigger(
            self._load_layout)
        self.bind(
            docked=self.setup_mode,
            have_shift=self._trigger_update_layout_mode,
            have_capslock=self._trigger_update_layout_mode,
            layout_path=self._trigger_load_layouts,
            layout=self._trigger_load_layout)
        self.register_event_type('on_key_down')
        self.register_event_type('on_key_up')
        super(VKeyboard, self).__init__(**kwargs)

        # load all the layouts found in the layout_path directory
        self._load_layouts()

        # ensure we have default layouts
        available_layouts = self.available_layouts
        if not available_layouts:
            Logger.critical('VKeyboard: unable to load default layouts')

        # load the default layout from configuration
        if self.layout is None:
            self.layout = Config.get('kivy', 'keyboard_layout')
        else:
            # ensure the current layout is found on the available layout
            self._trigger_load_layout()

        # update layout mode (shift or normal)
        self._trigger_update_layout_mode()

        # create a top layer to draw active keys on
        with self.canvas:
            self.background_key_layer = Canvas()
            self.active_keys_layer = Canvas()

        # prepare layout widget
        self.refresh_keys_hint()
        self.refresh_keys()
Пример #23
0
    def create_window(self, *largs):
        use_fake = self.fullscreen == 'fake'
        use_fullscreen = False

        if self.fullscreen in ('auto', True):
            use_fullscreen = self.fullscreen

        if not self.initialized:

            if self.position == 'auto':
                pos = None, None
            elif self.position == 'custom':
                pos = self.left, self.top

            # setup !
            w, h = self._size
            gl_size = self._win.setup_window(pos[0], pos[1], w, h,
                                             use_fake, use_fullscreen)
            # never stay with a None pos, application using w.center
            # will be fired.
            self._pos = (0, 0)
        else:
            w, h = self._size
            self._win.resize_window(w, h)

        super(WindowSDL, self).create_window()

        # auto add input provider
        Logger.info('Window: auto add sdl input provider')
        from kivy.base import EventLoop
        SDL2MotionEventProvider.win = self
        EventLoop.add_input_provider(SDL2MotionEventProvider('sdl', ''))

        # set window icon before calling set_mode
        try:
            filename_icon = self.icon or Config.get('kivy', 'window_icon')
            if filename_icon == '':
                logo_size = 32
                if platform == 'macosx':
                    logo_size = 512
                elif platform == 'win':
                    logo_size = 64
                filename_icon = 'kivy-icon-{}.png'.format(logo_size)
                filename_icon = resource_find(
                        join(kivy_data_dir, 'logo', filename_icon))
            self.set_icon(filename_icon)
        except:
            Logger.exception('Window: cannot set icon')
Пример #24
0
    def __init__(self, **kwargs):
        # XXX move to style.kv
        kwargs.setdefault("size_hint", (None, None))
        kwargs.setdefault("scale_min", 0.4)
        kwargs.setdefault("scale_max", 1.6)
        kwargs.setdefault("size", (700, 200))
        kwargs.setdefault("docked", False)
        self._trigger_update_layout_mode = Clock.create_trigger(self._update_layout_mode)
        self._trigger_load_layouts = Clock.create_trigger(self._load_layouts)
        self._trigger_load_layout = Clock.create_trigger(self._load_layout)
        self.bind(
            docked=self.setup_mode,
            have_shift=self._trigger_update_layout_mode,
            have_capslock=self._trigger_update_layout_mode,
            have_special=self._trigger_update_layout_mode,
            layout_path=self._trigger_load_layouts,
            layout=self._trigger_load_layout,
        )
        super(VKeyboard, self).__init__(**kwargs)

        # load all the layouts found in the layout_path directory
        self._load_layouts()

        # ensure we have default layouts
        available_layouts = self.available_layouts
        if not available_layouts:
            Logger.critical("VKeyboard: unable to load default layouts")

        # load the default layout from configuration
        if self.layout is None:
            self.layout = Config.get("kivy", "keyboard_layout")
        else:
            # ensure the current layout is found on the available layout
            self._trigger_load_layout()

        # update layout mode (shift or normal)
        self._trigger_update_layout_mode()

        # create a top layer to draw active keys on
        with self.canvas:
            self.background_key_layer = Canvas()
            self.active_keys_layer = Canvas()
Пример #25
0
    def configure_keyboards(self):
        # Configure how to provide keyboards (virtual or not)

        # register system keyboard to listening keys from window
        sk = self._system_keyboard
        self.bind(on_key_down=sk._on_window_key_down,
                  on_key_up=sk._on_window_key_up)

        # use the device's real keyboard
        self.allow_vkeyboard = False

        # one single vkeyboard shared between all widgets
        self.single_vkeyboard = True

        # the single vkeyboard is always sitting at the same position
        self.docked_vkeyboard = False

        # now read the configuration
        mode = Config.get('kivy', 'keyboard_mode')
        if mode not in ('', 'system', 'dock', 'multi'):
            Logger.critical('Window: unknown keyboard mode %r' % mode)

        # adapt mode according to the configuration
        if mode == 'system':
            self.allow_vkeyboard = False
            self.single_vkeyboard = True
            self.docked_vkeyboard = False
        elif mode == 'dock':
            self.allow_vkeyboard = True
            self.single_vkeyboard = True
            self.docked_vkeyboard = True
        elif mode == 'multi':
            self.allow_vkeyboard = True
            self.single_vkeyboard = False
            self.docked_vkeyboard = False

        Logger.info(
            'Window: virtual keyboard %sallowed, %s, %s' %
            ('' if self.allow_vkeyboard else 'not ',
             'single mode' if self.single_vkeyboard else 'multiuser mode',
             'docked' if self.docked_vkeyboard else 'not docked'))
Пример #26
0
    def arrancar_servicio(self):
        # Si el servicio ya estaba arrancado cuando la aplicación arranca,
        # volver a arrancarlo no tiene efecto, así que la lista de
        # alarmas del servicio sigue siendo la de la primera vez

        Logger.debug('%s: arrancar_servicio %s' % (APP, datetime.now()))

        self.parar_servicio()
        arg = {'pasadas': self.horario.pasadas,
               'alarmas': self.alarmas,
               'log_level': Config.get('kivy', 'log_level')}
        arg = dumps(arg)

        if platform == 'android':
            Logger.debug('%s: self.service = android.AndroidService(\
                \'Planilla\', \'Alarmas activas\')\')' % APP)
            self.service = android.AndroidService(
                'Planilla', 'Alarmas activas')
            Logger.debug('%s: self.service.start(arg)' % APP)
            self.service.start(arg)
            Logger.debug("%s: Arrancando servicio" % APP)
Пример #27
0
    def on_pre_enter(self, *args):
        """ Detect the current keyboard mode and set the text of the main
        label accordingly. """

        self.keyboard_mode = Config.get("kivy", "keyboard_mode")
        self.mode_spinner.text = "'{0}'".format(self.keyboard_mode)

        p1 = "Current keyboard mode: '{0}'\n\n".format(self.keyboard_mode)
        if self.keyboard_mode in ['dock', 'system', 'systemanddock']:
            p2 = "You have the right setting to use this demo.\n\n"
        else:
            p2 = "You need the keyboard mode to 'dock', 'system' or '"\
                 "'systemanddock'(below)\n in order to "\
                 "use custom onscreen keyboards.\n\n"

        p3 = "[b][color=#ff0000]Warning:[/color][/b] This is a system-wide " \
            "setting and will affect all Kivy apps. If you change the\n" \
            " keyboard mode, please use this app" \
            " to reset this value to it's original one."

        self.center_label.text = "".join([p1, p2, p3])
Пример #28
0
    def on_pre_enter(self, *args):
        """ Detect the current keyboard mode and set the text of the main
        label accordingly. """

        self.keyboard_mode = Config.get("kivy", "keyboard_mode")
        self.mode_spinner.text = "'{0}'".format(self.keyboard_mode)

        p1 = "Current keyboard mode: '{0}'\n\n".format(self.keyboard_mode)
        if self.keyboard_mode in ['dock', 'system', 'systemanddock']:
            p2 = "You have the right setting to use this demo.\n\n"
        else:
            p2 = "You need the keyboard mode to 'dock', 'system' or '"\
                 "'systemanddock'(below)\n in order to "\
                 "use custom onscreen keyboards.\n\n"

        p3 = "[b][color=#ff0000]Warning:[/color][/b] This is a system-wide " \
            "setting and will affect all Kivy apps. If you change the\n" \
            " keyboard mode, please use this app" \
            " to reset this value to it's original one."

        self.center_label.text = "".join([p1, p2, p3])
Пример #29
0
    def __init__(self, **kwargs):
        self.pageNumber = 1
        self.picktypes = menu.keys()
        #self.soustypes = sous_menu.get(kwargs['types']).keys()
        self.view = Config.get('user', 'view')

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

        #grille de poster
        #self.grid = self.grid_l
        self.menu = kwargs['menu']
        self.types = kwargs['types']

        app = App.get_running_app()

        self.ids.discover_label.text = app._(kwargs['menu'])

        EXlog((self.menu, self.types))

        #poster
        self.ids.grid_id.clear_widgets()
        self.add()
Пример #30
0
    def create_window(self, *largs):
        use_fake = self.fullscreen == 'fake'
        use_fullscreen = False
        if self.fullscreen in ('auto', True):
            use_fullscreen = self.fullscreen

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

            # setup !
            w, h = self._size
            gl_size = self._win.setup_window(w, h, use_fake, use_fullscreen)
        else:
            w, h = self._size
            self._win.resize_window(w, h)

        super(WindowSDL, self).create_window()

        # auto add input provider
        Logger.info('Window: auto add sdl input provider')
        from kivy.base import EventLoop
        SDL2MotionEventProvider.win = self
        EventLoop.add_input_provider(SDL2MotionEventProvider('sdl', ''))

        # set window icon before calling set_mode
        try:
            filename_icon = self.icon or Config.get('kivy', 'window_icon')
            if filename_icon == '':
                logo_size = 32
                if platform == 'macosx':
                    logo_size = 512
                elif platform == 'win':
                    logo_size = 64
                filename_icon = 'kivy-icon-{}.png'.format(logo_size)
                filename_icon = resource_find(
                    join(kivy_data_dir, 'logo', filename_icon))
            self.set_icon(filename_icon)
        except:
            Logger.exception('Window: cannot set icon')
Пример #31
0
 def __init__(self, **kwargs):
     self._win = None
     if 'min_state_time' not in kwargs:
         self.min_state_time = float(
             Config.get('graphics', 'min_state_time'))
     if 'container' not in kwargs:
         c = self.container = Builder.load_string(_grid_kv)
     else:
         c = None
     if 'do_scroll_x' not in kwargs:
         self.do_scroll_x = False
     if 'size_hint' not in kwargs:
         if 'size_hint_x' not in kwargs:
             self.size_hint_x = None
         if 'size_hint_y' not in kwargs:
             self.size_hint_y = None
     super(DropDown, self).__init__(**kwargs)
     if c is not None:
         super(DropDown, self).add_widget(c)
         self.on_container(self, c)
     Window.bind(on_key_down=self.on_key_down, size=self._reposition)
     self.fbind('size', self._reposition)
Пример #32
0
def _setup_locale():
    """ Setting up localization
    :return: translation method
    """
    try:
        locale_file = Config.get('xpopup', 'locale_file')
    except:
        from os.path import abspath, dirname, join
        locale_file = join(dirname(abspath(__file__)), 'xpopup.mo')

    try:
        with open(locale_file, "rb") as f:
            xpopup_locale = gettext.GNUTranslations(f)
        Logger.info('Localization file loaded (%s).' % locale_file)
    except Exception as e:
        Logger.warning('%s: %s. Switch to the defaults.' %
                       (e.__class__.__name__, str(e)))
        xpopup_locale = gettext.NullTranslations()

    if PY2:
        return xpopup_locale.ugettext
    else:
        return xpopup_locale.gettext
Пример #33
0
    def arrancar_servicio(self):
        # Si el servicio ya estaba arrancado cuando la aplicación arranca,
        # volver a arrancarlo no tiene efecto, así que la lista de
        # alarmas del servicio sigue siendo la de la primera vez

        Logger.debug('%s: arrancar_servicio %s' % (APP, datetime.now()))

        self.parar_servicio()
        arg = {
            'pasadas': self.horario.pasadas,
            'alarmas': self.alarmas,
            'log_level': Config.get('kivy', 'log_level')
        }
        arg = dumps(arg)

        if platform == 'android':
            Logger.debug('%s: self.service = android.AndroidService(\
                \'Planilla\', \'Alarmas activas\')\')' % APP)
            self.service = android.AndroidService('Planilla',
                                                  'Alarmas activas')
            Logger.debug('%s: self.service.start(arg)' % APP)
            self.service.start(arg)
            Logger.debug("%s: Arrancando servicio" % APP)
Пример #34
0
    def _load_sound_cfg(self, cfgName):
        path = ""
        try:
            path = os.path.join(self.directory,
                                Config.get("media_sounds", cfgName))
        except ValueError:
            Logger.error(f"SoundBoard: Missing sound configuration {cfgName}")
            raise

        if not os.path.exists(path):
            Logger.error(
                f"SoundBoard: Invalid path to sound Path = {path} Configuration = {cfgName}"
            )
            raise ValueError(f"Invalid path {path}")
        Logger.info(
            f"SoundBoard: attempting to load sound {cfgName} from path {path}")
        sound = self.loader.load(path)
        if not sound:
            Logger.error(
                f"SoundBoard: Failed to load sound {path} from {cfgName}")
            raise ValueError(f"Failed to load sound {path} from {cfgName}")

        Logger.info(f"SoundBoard: Loaded {cfgName} from path {path}")
        return sound
Пример #35
0
    def build(self):
        self.light_control_client = LightController(Config.get(
            "light_controls", "ip_address"),
                                                    81,
                                                    debug=True)

        if Config.getboolean("light_controls", "device_enabled"):
            self.light_control_client.start()

        self.weather_service = WeatherService()
        self.weather_service.start()

        self.sm = CustomScreenManager()

        self.main_screen = MainScreen(name="main")
        self.sm.add_widget(self.main_screen)

        self.settings_screen = SettingsScreen(name="settings")
        self.sm.add_widget(self.settings_screen)

        self.idle_screen = IdleScreen(name="idle")
        self.sm.add_widget(self.idle_screen)

        return self.sm
Пример #36
0
class NavigationController(BoxLayout):
    '''
    Custom layout you can use to manage navigation in your app.
    This is inspired by iOS navigation system, but much easier...

    You should put a NavigationController as root widget for your app,
    internally uses a stack to manage navigation ( accessible by using the 'stack' property ).

    You can pop\push views by using 'pop' and 'push' methods.
    '''

    root_widget = ObjectProperty(None)
    '''
    The current widget is stored here.
    '''

    stack = ListProperty([])
    '''
    Stack used to navigate between various screens\widgets.
    '''

    background_color = ListProperty([.93, .93, .93, 1])
    '''
    Solid background color.
    '''

    animation_duracy = NumericProperty(.25)
    '''
    Push & pop animation duracy, default 0.25 seconds.
    '''

    push_mode = OptionProperty('right', options=['left', 'right'])
    '''
    Left or right, will push/pop views from/to the given direction.
    '''

    disable_widget = BooleanProperty(False)
    '''
    If true, root widget will be disabled during animations.
    This will hide animations!
    '''

    #Navigation bar

    title = StringProperty('Navigation control!')
    '''
    Navigation bar title.
    '''

    nav_height = NumericProperty(dp(56))
    '''
    Navigation bar height.
    '''

    #    nav_color = ListProperty( [ .54, .765, .86, 1] )
    nav_color = ListProperty([.1, .11, .11, 1])
    '''
    Navigation bar color.
    '''

    shadow_alpha = NumericProperty(.065)
    '''
    Alpha channel for navigation bar shadow.
    '''

    font_name = StringProperty(None)
    '''
    Navigation bar font name.
    '''

    font_size = NumericProperty(dp(22))
    '''
    Navigation bar font size.
    '''

    text_color = ListProperty([1, 1, 1, 1])
    '''
    Navigation bar text color.
    '''

    floating_panel = ObjectProperty(None)
    '''
    FloatingLayout you can use for any pourpose.
    '''

    splash_image = StringProperty(alphapng)
    '''
    Image used as splash screen.
    '''

    #Private stuffs...
    _push_cache = ListProperty([])
    _actionprev = ObjectProperty(None)
    _actiontext = ObjectProperty(None)
    _content = ObjectProperty(None)
    _width = NumericProperty(float(Config.get('graphics', 'width')))

    def __init__(self, **kargs):
        super(NavigationController, self).__init__(**kargs)
        self._keyboard_show = False
        self._keyboard_just_show = False
        self._has_root = False
        self._last_args = {'title': '', 'animation': None}
        self._animation = None
        self._bind_keyboard()

    def pop(self, *args):
        '''
        Use this to go back to the last view.
        Will eventually throw EmptyNavigationStack.
        '''
        #        pdb.set_trace()
        if self._animation is None:
            if len(self.stack) > 0:
                try:
                    self.root_widget.on_pop(self)
                except:
                    pass
                self._save_temp_view(0, self.root_widget)
                self._run_pop_animation()
            else:
                raise EmptyNavigationStack()

    def push(self, view, **kargs):
        '''
        Will append the last view to the list and show the new one.
        Keyword arguments :
            title
                Navigation bar title, default ''.
        '''

        if self._animation is None:
            if not 'title' in kargs.keys(): kargs['title'] = ''
            self._last_kargs = kargs
            x = -1 if self.push_mode == 'left' else 1
            self._save_temp_view(x, view)
            self._run_push_animation()

#================================================================================
# Private stuff of various use...
#================================================================================

    def _bind_keyboard(self):
        EventLoop.window.bind(on_keyboard=self._on_keyboard_show)
        EventLoop.window.bind(on_key_down=self._on_keyboard_down)

    def _on_keyboard_show(self, *args):
        self._keyboard_show = True

    def _on_keyboard_down(self, window, key, *args):

        if key == 27:
            if self._keyboard_show:
                self._keyboard_show = False
                EventLoop.window.release_all_keyboards()
            else:
                self.pop()
            return True
        return False

    def _run_push_animation(self):
        try:
            self._temp_view.disabled = self.disable_widget
            duracy = self.animation_duracy if self._has_root else 0
            self._animation = Animation(x=0, duration=duracy)
            self._animation.bind(on_complete=self._push_temp_view)
            self._animation.start(self._temp_view)
        except:
            pass  #Exception as e : print(e)

    def _run_pop_animation(self):
        try:
            self._temp_view.disabled = self.disable_widget
            x = self._temp_view.width * (-1 if self.push_mode == 'left' else 1)
            self._animation = Animation(x=x, duration=self.animation_duracy)
            self._animation.bind(on_complete=self._pop_temp_view)
            self._animation.start(self._temp_view)
        except:
            pass  #Exception as e : print(e)

    def _push_temp_view(self, *args):
        self._temp_view.disabled = False

        if self._has_root:
            self.content.remove_widget(self.root_widget)

        self.stack.append([self.root_widget, self._last_kargs])
        self.root_widget = self._temp_view
        self._clear_temp_view()
        self.content.add_widget(self.root_widget)
        self._has_root = True
        self._update_nav()
        self._animation = None
        try:
            self.root_widget.on_push(self)
        except:
            pass

    def _pop_temp_view(self, *args):
        self._temp_view.disabled = False
        self.content.remove_widget(self.root_widget)
        self.root_widget, self._last_kargs = self.stack.pop()
        if len(self.stack) > 0: self._last_kargs = self.stack[-1][1]
        self.content.add_widget(self.root_widget)
        self._update_nav()
        self._animation = None

    def _clear_temp_view(self, *args):
        try:
            self.floating_panel.remove_widget(self._temp_view)
        except:
            pass
        self._temp_view = None

    def _save_temp_view(self, p, view):
        self._temp_view = view
        try:
            self._temp_view.pos = [self._width * p, 0]
            self.floating_panel.add_widget(self._temp_view)
        except:
            pass

    def _update_nav(self):
        self.title = self._last_kargs['title']
        has_previous = len(self.stack) > 1
        self.actionprev.text = ' < ' if has_previous else ''
        #self.actionprev.icon = icon_back_32 if has_previous else ''
        self.actionprev.disabled = not has_previous
Пример #37
0
class WindowPygame(WindowBase):

    def create_window(self, *largs):
        # ensure the mouse is still not up after window creation, otherwise, we
        # have some weird bugs
        self.dispatch('on_mouse_up', 0, 0, 'all', [])

        # force display to show (available only for fullscreen)
        displayidx = Config.getint('graphics', 'display')
        if not 'SDL_VIDEO_FULLSCREEN_HEAD' in environ and displayidx != -1:
            environ['SDL_VIDEO_FULLSCREEN_HEAD'] = '%d' % displayidx

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

        # right now, activate resizable window only on linux.
        # on window / macosx, the opengl context is lost, and we need to
        # reconstruct everything. Check #168 for a state of the work.
        if platform() in ('linux', 'macosx', 'win') and \
            Config.getint('graphics', 'resizable'):
            self.flags |= pygame.RESIZABLE

        try:
            pygame.display.init()
        except pygame.error, e:
            raise CoreCriticalException(e.message)

        multisamples = 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.set_caption(self.title)

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

        if self.fullscreen == 'fake':
            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)
            environ['SDL_VIDEO_WINDOW_POS'] = '%d,%d' % self._pos

        elif self.fullscreen in ('auto', True):
            Logger.debug('WinPygame: Set window to fullscreen mode')
            self.flags |= pygame.FULLSCREEN

        elif self._pos is not None:
            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(Config.get('kivy', 'keyboard_repeat_delay'))
        repeat_rate = float(Config.get('kivy', 'keyboard_repeat_rate'))
        pygame.key.set_repeat(repeat_delay, int(1000. / repeat_rate))

        # set window icon before calling set_mode
        try:
            #filename_icon = Config.get('kivy', 'window_icon')
            filename_icon = self.icon or Config.get('kivy', 'window_icon')
            if filename_icon == '':
                logo_size = 512 if platform() == 'macosx' else 32
                filename_icon = join(kivy_home_dir, 'icon', 'kivy-icon-%d.png' %
                        logo_size)
            self.set_icon(filename_icon)
        except:
            Logger.exception('Window: cannot set icon')

        # try to use mode with multisamples
        try:
            self._pygame_set_mode()
        except pygame.error, e:
            if multisamples:
                Logger.warning('WinPygame: Video: failed (multisamples=%d)' %
                               multisamples)
                Logger.warning('WinPygame: trying without antialiasing')
                pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 0)
                pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 0)
                multisamples = 0
                try:
                    self._pygame_set_mode()
                except pygame.error, e:
                    raise CoreCriticalException(e.message)
Пример #38
0
 def __init__(self, board, **kwargs):
     print("Tableau d'arguments de Board : {}".format(kwargs))
     self.board = board
     super(Board, self).__init__(**kwargs)
     self.size = (Config.get('graphics',
                             'width'), Config.get('graphics', 'height'))
Пример #39
0
            mkdir(kivy_home_dir)
        if not exists(kivy_usermodules_dir):
            mkdir(kivy_usermodules_dir)
        if not exists(kivy_userexts_dir):
            mkdir(kivy_userexts_dir)
        if not exists(icon_dir):
            try:
                shutil.copytree(join(kivy_data_dir, 'logo'), icon_dir)
            except shutil.Error, e:
                Logger.exception('Error when copying logo directory')

    # configuration
    from kivy.config import Config

    # Set level of logger
    level = LOG_LEVELS.get(Config.get('kivy', 'log_level'))
    Logger.setLevel(level=level)
    Logger.setLevel(level=LOG_LEVELS.get('debug'))

    # Can be overrided in command line
    if 'KIVY_UNITTEST' not in environ:

        # save sys argv, otherwize, gstreamer use it and display help..
        sys_argv = sys.argv
        sys.argv = sys.argv[:1]

        try:
            opts, args = getopt(sys_argv[1:], 'hp:fkawFem:sr:dc:', [
                'help', 'fullscreen', 'windowed', 'fps', 'event', 'module=',
                'save', 'fake-fullscreen', 'auto-fullscreen', 'display=',
                'size=', 'rotate=', 'config=', 'debug'
Пример #40
0
    def create_window(self, *largs):
        if self._fake_fullscreen:
            if not self.borderless:
                self.fullscreen = self._fake_fullscreen = False
            elif not self.fullscreen or self.fullscreen == 'auto':
                self.borderless = self._fake_fullscreen = False
        if self.fullscreen == 'fake':
            self.borderless = self._fake_fullscreen = True
            Logger.warning("The 'fake' fullscreen option has been "
                           "deprecated, use Window.borderless or the "
                           "borderless Config option instead.")

        if not self.initialized:
            if self.position == 'auto':
                pos = None, None
            elif self.position == 'custom':
                pos = self.left, self.top

            # ensure we have an event filter
            self._win.set_event_filter(self._event_filter)

            # setup window
            w, h = self.system_size
            resizable = Config.getboolean('graphics', 'resizable')
            state = (Config.get('graphics', 'window_state')
                     if self._is_desktop else None)
            self.system_size = _size = self._win.setup_window(
                pos[0], pos[1], w, h, self.borderless, self.fullscreen,
                resizable, state, self.get_gl_backend_name())

            # calculate density
            sz = self._win._get_gl_size()[0]
            self._density = density = sz / _size[0]
            if self._is_desktop and self.size[0] != _size[0]:
                self.dpi = density * 96.

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

            if state == 'hidden':
                self._focus = False
        else:
            w, h = self.system_size
            self._win.resize_window(w, h)
            self._win.set_border_state(self.borderless)
            self._win.set_fullscreen_mode(self.fullscreen)

        super(WindowSDL, self).create_window()
        # set mouse visibility
        self._set_cursor_state(self.show_cursor)

        if self.initialized:
            return

        # auto add input provider
        Logger.info('Window: auto add sdl2 input provider')
        from kivy.base import EventLoop
        SDL2MotionEventProvider.win = self
        EventLoop.add_input_provider(SDL2MotionEventProvider('sdl', ''))

        # set window icon before calling set_mode
        try:
            filename_icon = self.icon or Config.get('kivy', 'window_icon')
            if filename_icon == '':
                logo_size = 32
                if platform == 'macosx':
                    logo_size = 512
                elif platform == 'win':
                    logo_size = 64
                filename_icon = 'kivy-icon-{}.png'.format(logo_size)
                filename_icon = resource_find(
                    join(kivy_data_dir, 'logo', filename_icon))
            self.set_icon(filename_icon)
        except:
            Logger.exception('Window: cannot set icon')
Пример #41
0
    def __init__(self, **kwargs):

        kwargs.setdefault('force', False)

        # don't init window 2 times,
        # except if force is specified
        if WindowBase.__instance is not None and not kwargs.get('force'):
            return

        self.initialized = False
        self._is_desktop = Config.getboolean('kivy', 'desktop')

        # create a trigger for update/create the window when one of window
        # property changes
        self.trigger_create_window = Clock.create_trigger(
            self.create_window, -1)

        # Create a trigger for updating the keyboard height
        self.trigger_keyboard_height = Clock.create_trigger(
            self._upd_kbd_height, .5)

        # set the default window parameter according to the configuration
        if 'borderless' not in kwargs:
            kwargs['borderless'] = Config.getboolean('graphics', 'borderless')
        if 'fullscreen' not in kwargs:
            fullscreen = Config.get('graphics', 'fullscreen')
            if fullscreen not in ('auto', 'fake'):
                fullscreen = fullscreen.lower() in ('true', '1', 'yes', 'yup')
            kwargs['fullscreen'] = fullscreen
        if 'width' not in kwargs:
            kwargs['width'] = Config.getint('graphics', 'width')
        if 'height' not in kwargs:
            kwargs['height'] = Config.getint('graphics', 'height')
        if 'rotation' not in kwargs:
            kwargs['rotation'] = Config.getint('graphics', 'rotation')
        if 'position' not in kwargs:
            kwargs['position'] = Config.getdefault('graphics', 'position',
                                                   'auto')
        if 'top' in kwargs:
            kwargs['position'] = 'custom'
            kwargs['top'] = kwargs['top']
        else:
            kwargs['top'] = Config.getint('graphics', 'top')
        if 'left' in kwargs:
            kwargs['position'] = 'custom'
            kwargs['left'] = kwargs['left']
        else:
            kwargs['left'] = Config.getint('graphics', 'left')
        kwargs['_size'] = (kwargs.pop('width'), kwargs.pop('height'))

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

        # bind all the properties that need to recreate the window
        self._bind_create_window()
        self.bind(size=self.trigger_keyboard_height,
                  rotation=self.trigger_keyboard_height)

        self.bind(softinput_mode=lambda *dt: self.update_viewport(),
                  keyboard_height=lambda *dt: self.update_viewport())

        # init privates
        self._system_keyboard = Keyboard(window=self)
        self._keyboards = {'system': self._system_keyboard}
        self._vkeyboard_cls = None

        self.children = []
        self.parent = self

        # before creating the window
        import kivy.core.gl  # NOQA

        # configure the window
        self.create_window()

        # attach modules + listener event
        EventLoop.set_window(self)
        Modules.register_window(self)
        EventLoop.add_event_listener(self)

        # manage keyboard(s)
        self.configure_keyboards()

        # assign the default context of the widget creation
        if not hasattr(self, '_context'):
            self._context = get_current_context()

        # mark as initialized
        self.initialized = True
 def __init__(self):
     self.ignore_list = strtotuple(Config.get('postproc', 'ignore'))
Пример #43
0
 def __init__(self):
     self.jitterdist = Config.getfloat('postproc', 'jitter_distance')
     ignore_devices = Config.get('postproc', 'jitter_ignore_devices')
     self.ignore_devices = ignore_devices.split(',')
     self.last_touches = {}
Пример #44
0
# Set the window size on a new computer and make launch the readme if at the first launch.
from win32api import GetSystemMetrics
from os import environ, startfile, getcwd
environ['KIVY_HOME'] = '../save'
from kivy.config import Config
first_open = Config.get('kivy', 'first_open')
from logging import info
if first_open == 'True':
    info('Detected first opening. Launching readme.md')
    path = getcwd()
    startfile(path + '/../README.md')
    Config.set('graphics', 'width', int(GetSystemMetrics(0) * 2 / 3))
    Config.set('graphics', 'height', int(GetSystemMetrics(1) * 2 / 3))
    Config.set('kivy', 'first_open', False)
    Config.write()

# Regular imports
from io import BytesIO
from kivy.app import App
from kivy.clock import Clock
from kivy.animation import Animation
from kivy.properties import NumericProperty, BooleanProperty
from kivy.uix.popup import Popup
from kivy.uix.relativelayout import RelativeLayout
from src.database import get_table, use, get_columns
from kivy.core.image import Image as CoreImage
from wordcloud import WordCloud


# To hook into styling; Look in .kv
class PermissionPopup(Popup):
Пример #45
0
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     Config.get('kivy', 'keyboard_mode'),
     Config.get('kivy', 'keyboard_layout')
Пример #46
0
if __name__ == '__main__':

    root = FloatLayout()

    # create a button to release everything
    def release_all_keyboard(*l):
        Window.release_all_keyboards()

    btn = Button(text='Release\nall\nkeyboards',
                 size_hint=(None, None),
                 halign='center')
    btn.bind(on_release=release_all_keyboard)
    root.add_widget(btn)

    # show current configuration
    lbl = 'Configuration keyboard_mode is %r, keyboard_layout is %r' % (
        Config.get('kivy',
                   'keyboard_mode'), Config.get('kivy', 'keyboard_layout'))
    label = Label(text=lbl, size_hint_y=None, height=50, pos_hint={'top': 1})
    root.add_widget(label)

    s = Scatter(size_hint=(None, None), pos=(300, 300))
    s.add_widget(TextInput(size_hint=(None, None), size=(100, 50)))
    root.add_widget(s)

    s = Scatter(size_hint=(None, None), pos=(400, 300), rotation=45)
    s.add_widget(TextInput(size_hint=(None, None), size=(100, 50)))
    root.add_widget(s)

    runTouchApp(root)
Пример #47
0
    def __init__(self, **kwargs):

        kwargs.setdefault('force', False)

        # don't init window 2 times,
        # except if force is specified
        if WindowBase.__instance is not None and not kwargs.get('force'):
            return
        self.initialized = False

        # create a trigger for update/create the window when one of window
        # property changes
        self.trigger_create_window = Clock.create_trigger(
                self.create_window, -1)

        # set the default window parameter according to the configuration
        if 'fullscreen' not in kwargs:
            fullscreen = Config.get('graphics', 'fullscreen')
            if fullscreen not in ('auto', 'fake'):
                fullscreen = fullscreen.lower() in ('true', '1', 'yes', 'yup')
            kwargs['fullscreen'] = fullscreen
        if 'width' not in kwargs:
            kwargs['width'] = Config.getint('graphics', 'width')
        if 'height' not in kwargs:
            kwargs['height'] = Config.getint('graphics', 'height')
        if 'rotation' not in kwargs:
            kwargs['rotation'] = Config.getint('graphics', 'rotation')
        if 'position' not in kwargs:
            kwargs['position'] = Config.getdefault('graphics', 'position', 'auto')
        if 'top' in kwargs:
            kwargs['position'] = 'custom'
            kwargs['top'] = kwargs['top']
        else:
            kwargs['top'] = Config.getint('graphics', 'top')
        if 'left' in kwargs:
            kwargs['position'] = 'custom'
            kwargs['left'] = kwargs['left']
        else:
            kwargs['left'] = Config.getint('graphics', 'left')
        kwargs['_size'] = (kwargs.pop('width'), kwargs.pop('height'))

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

        # bind all the properties that need to recreate the window
        for prop in (
                'fullscreen', 'position', 'top',
                'left', '_size', 'system_size'):
            self.bind(**{prop: self.trigger_create_window})

        # init privates
        self._system_keyboard = Keyboard(window=self)
        self._keyboards = {'system': self._system_keyboard}
        self._vkeyboard_cls = None

        self.children = []
        self.parent = self

        # before creating the window
        import kivy.core.gl

        # configure the window
        self.create_window()

        # attach modules + listener event
        EventLoop.set_window(self)
        Modules.register_window(self)
        EventLoop.add_event_listener(self)

        # manage keyboard(s)
        self.configure_keyboards()

        # mark as initialized
        self.initialized = True
Пример #48
0
        info = win32api.GetMonitorInfo(monitor[0])
        (x, t, r, y) = info['Work']
        monitor_positions.insert(0, (x, t, r, y))
else:
    raise Exception("Running on unsupported Platform!")

(x, y, r, t) = monitor_positions[0]
sw, sh = r - x, t - y
Config.set('graphics', 'position', 'custom')
Config.set('graphics', 'left', int(x + sw / 2 - sw * 0.09))
Config.set('graphics', 'top', int(y + sh / 2 - sh * 0.14))
Config.set('graphics', 'borderless', 0)

from configparser import NoOptionError
try:
    if width != int(Config.get('graphics', 'screen_width')) or height != int(
            Config.get('graphics', 'screen_height')):
        Config.set('graphics', 'screen_width', width)
        Config.set('graphics', 'screen_height', height)
except NoOptionError:
    Config.set('graphics', 'screen_width', width)
    Config.set('graphics', 'screen_height', height)

Config.set('graphics', 'width', int(width * 0.18))
Config.set('graphics', 'minimum_width', int(width * 0.18))
Config.set('graphics', 'height', int(height * 0.28))
Config.set('graphics', 'minimum_height', int(height * 0.28))
Config.set('graphics', 'fullscreen', 0)
Config.set('graphics', 'borderless', 0)
play_game = False
Пример #49
0
    def _load_urllib(self, filename, kwargs):
        '''(internal) Loading a network file. First download it, save it to a
        temporary file, and pass it to _load_local().'''
        if PY2:
            import urllib2 as urllib_request

            def gettype(info):
                return info.gettype()
        else:
            import urllib.request as urllib_request

            def gettype(info):
                return info.get_content_type()
        proto = filename.split(':', 1)[0]
        if proto == 'smb':
            try:
                # note: it's important to load SMBHandler every time
                # otherwise the data is occasionally not loaded
                from smb.SMBHandler import SMBHandler
            except ImportError:
                Logger.warning(
                    'Loader: can not load PySMB: make sure it is installed')
                return
        import tempfile
        data = fd = _out_osfd = None
        try:
            _out_filename = ''

            if proto == 'smb':
                # read from samba shares
                fd = urllib_request.build_opener(SMBHandler).open(filename)
            else:
                # read from internet
                request = urllib_request.Request(filename)
                if (
                    Config.has_section('network')
                    and 'useragent' in Config.items('network')
                ):
                    useragent = Config.get('network', 'useragent')
                    if useragent:
                        request.add_header('User-Agent', useragent)
                opener = urllib_request.build_opener()
                fd = opener.open(request)

            if '#.' in filename:
                # allow extension override from URL fragment
                suffix = '.' + filename.split('#.')[-1]
            else:
                ctype = gettype(fd.info())
                suffix = mimetypes.guess_extension(ctype)
                if not suffix:
                    # strip query string and split on path
                    parts = filename.split('?')[0].split('/')[1:]
                    while len(parts) > 1 and not parts[0]:
                        # strip out blanks from '//'
                        parts = parts[1:]
                    if len(parts) > 1 and '.' in parts[-1]:
                        # we don't want '.com', '.net', etc. as the extension
                        suffix = '.' + parts[-1].split('.')[-1]
            _out_osfd, _out_filename = tempfile.mkstemp(
                prefix='kivyloader', suffix=suffix)

            idata = fd.read()
            fd.close()
            fd = None

            # write to local filename
            write(_out_osfd, idata)
            close(_out_osfd)
            _out_osfd = None

            # load data
            data = self._load_local(_out_filename, kwargs)

            # FIXME create a clean API for that
            for imdata in data._data:
                imdata.source = filename
        except Exception as ex:
            Logger.exception('Loader: Failed to load image <%s>' % filename)
            # close file when remote file not found or download error
            try:
                if _out_osfd:
                    close(_out_osfd)
            except OSError:
                pass

            # update client
            for c_filename, client in self._client[:]:
                if filename != c_filename:
                    continue
                # got one client to update
                client.image = self.error_image
                client.dispatch('on_error', error=ex)
                self._client.remove((c_filename, client))

            return self.error_image
        finally:
            if fd:
                fd.close()
            if _out_osfd:
                close(_out_osfd)
            if _out_filename != '':
                unlink(_out_filename)

        return data
Пример #50
0
            mkdir(kivy_home_dir)
        if not exists(kivy_usermodules_dir):
            mkdir(kivy_usermodules_dir)
        if not exists(kivy_userexts_dir):
            mkdir(kivy_userexts_dir)
        if not exists(icon_dir):
            try:
                shutil.copytree(join(kivy_data_dir, 'logo'), icon_dir)
            except:
                Logger.exception('Error when copying logo directory')

    # configuration
    from kivy.config import Config

    # Set level of logger
    level = LOG_LEVELS.get(Config.get('kivy', 'log_level'))
    Logger.setLevel(level=level)
    Logger.setLevel(level=LOG_LEVELS.get('debug'))

    # Can be overrided in command line
    if 'KIVY_UNITTEST' not in environ and 'KIVY_PACKAGING' not in environ:
        # save sys argv, otherwize, gstreamer use it and display help..
        sys_argv = sys.argv
        sys.argv = sys.argv[:1]

        try:
            opts, args = getopt(sys_argv[1:], 'hp:fkawFem:sr:dc:', [
                'help', 'fullscreen', 'windowed', 'fps', 'event',
                'module=', 'save', 'fake-fullscreen', 'auto-fullscreen',
                'display=', 'size=', 'rotate=', 'config=', 'debug',
                'dpi='])
Пример #51
0
    future version.
'''

__all__ = ('FocusBehavior', )

from kivy.properties import OptionProperty, ObjectProperty, BooleanProperty, \
    AliasProperty
from kivy.config import Config
from kivy.base import EventLoop

# When we are generating documentation, Config doesn't exist
_is_desktop = False
_keyboard_mode = 'system'
if Config:
    _is_desktop = Config.getboolean('kivy', 'desktop')
    _keyboard_mode = Config.get('kivy', 'keyboard_mode')


class FocusBehavior(object):
    '''Provides keyboard focus behavior. When combined with other
    FocusBehavior widgets it allows one to cycle focus among them by pressing
    tab. Please see the
    :mod:`focus behavior module documentation <kivy.uix.behaviors.focus>`
    for more information.

    .. versionadded:: 1.9.0

    '''

    _requested_keyboard = False
    _keyboard = ObjectProperty(None, allownone=True)
Пример #52
0
SYSTEM_IDS = [
    'accio', 'aguamenti', 'expecto patronum', 'diffindo', 'episkey',
    'expelliarmus', 'impedimenta', 'protego', 'revelio', 'tergeo', 'lumos',
    'veritaserum', 'muffliato', 'alohomora', 'test'
]
GOOGLE_SPREADSHEET_ID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

# set app icon
from kivy.config import Config
from os.path import dirname, join

CURDIR = dirname(__file__)
icon_path = join(CURDIR, 'icons', 'simpleicon.png')
Config.set('kivy', 'window_icon', icon_path)
LOG_DIR = Config.get('kivy', 'log_dir')
LOG_NAME = Config.get('kivy', 'log_name')
CONFIG_FILE = join(CURDIR, 'kivycam.ini')
Пример #53
0
from ast import literal_eval
from functools import partial
from copy import copy
from kivy import kivy_data_dir
from kivy.config import Config
from kivy.utils import platform
from kivy.graphics.texture import Texture
from kivy.core import core_select_lib
from kivy.core.text.text_layout import layout_text, LayoutWord
from kivy.resources import resource_find, resource_add_path
from kivy.compat import PY2
from kivy.setupconfig import USE_SDL2, USE_PANGOFT2


if 'KIVY_DOC' not in os.environ:
    _default_font_paths = literal_eval(Config.get('kivy', 'default_font'))
    DEFAULT_FONT = _default_font_paths.pop(0)
else:
    DEFAULT_FONT = None

FONT_REGULAR = 0
FONT_ITALIC = 1
FONT_BOLD = 2
FONT_BOLDITALIC = 3

whitespace_pat = re.compile('( +)')


class LabelBase(object):
    '''Core text label.
    This is the abstract class used by different backends to render text.
    def _load_urllib(self, filename, kwargs):
        '''(internal) Loading a network file. First download it, save it to a
        temporary file, and pass it to _load_local().'''
        if PY2:
            import urllib2 as urllib_request

            def gettype(info):
                return info.gettype()
        else:
            import urllib.request as urllib_request

            def gettype(info):
                return info.get_content_type()

        proto = filename.split(':', 1)[0]
        if proto == 'smb':
            try:
                # note: it's important to load SMBHandler every time
                # otherwise the data is occasionally not loaded
                from smb.SMBHandler import SMBHandler
            except ImportError:
                Logger.warning(
                    'Loader: can not load PySMB: make sure it is installed')
                return
        import tempfile
        data = fd = _out_osfd = None
        try:
            _out_filename = ''

            if proto == 'smb':
                # read from samba shares
                fd = urllib_request.build_opener(SMBHandler).open(filename)
            else:
                # read from internet
                request = urllib_request.Request(filename)
                if (Config.has_section('network')
                        and 'useragent' in Config.items('network')):
                    useragent = Config.get('network', 'useragent')
                    if useragent:
                        request.add_header('User-Agent', useragent)
                opener = urllib_request.build_opener()
                fd = opener.open(request)

            if '#.' in filename:
                # allow extension override from URL fragment
                suffix = '.' + filename.split('#.')[-1]
            else:
                ctype = gettype(fd.info())
                suffix = mimetypes.guess_extension(ctype)
                suffix = LoaderBase.EXT_ALIAS.get(suffix, suffix)
                if not suffix:
                    # strip query string and split on path
                    parts = filename.split('?')[0].split('/')[1:]
                    while len(parts) > 1 and not parts[0]:
                        # strip out blanks from '//'
                        parts = parts[1:]
                    if len(parts) > 1 and '.' in parts[-1]:
                        # we don't want '.com', '.net', etc. as the extension
                        suffix = '.' + parts[-1].split('.')[-1]
            _out_osfd, _out_filename = tempfile.mkstemp(prefix='kivyloader',
                                                        suffix=suffix)

            idata = fd.read()
            fd.close()
            fd = None

            # write to local filename
            write(_out_osfd, idata)
            close(_out_osfd)
            _out_osfd = None

            # load data
            data = self._load_local(_out_filename, kwargs)

            # FIXME create a clean API for that
            for imdata in data._data:
                imdata.source = filename
        except Exception as ex:
            Logger.exception('Loader: Failed to load image <%s>' % filename)
            # close file when remote file not found or download error
            try:
                if _out_osfd:
                    close(_out_osfd)
            except OSError:
                pass

            # update client
            for c_filename, client in self._client[:]:
                if filename != c_filename:
                    continue
                # got one client to update
                client.image = self.error_image
                client.dispatch('on_error', error=ex)
                self._client.remove((c_filename, client))

            return self.error_image
        finally:
            if fd:
                fd.close()
            if _out_osfd:
                close(_out_osfd)
            if _out_filename != '':
                unlink(_out_filename)

        return data
Пример #55
0
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.dropdown import DropDown
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.checkbox import CheckBox
from kivy.config import Config
from kivy.properties import ObjectProperty, NumericProperty, \
    BooleanProperty, StringProperty, ListProperty, OptionProperty
from kivy.uix.spinner import Spinner
from kivy.lang import Builder
from functools import partial

window_icon = ''
if Config:
    window_icon = Config.get('kivy', 'window_icon')


class ActionBarException(Exception):
    '''ActionBarException class
    '''
    pass


class ActionItem(object):
    '''ActionItem class, an abstract class for all ActionBar widgets. To create
       a custom widget for an ActionBar, inherit from this
       class. See module documentation for more information.
    '''

    minimum_width = NumericProperty('90sp')
Пример #56
0
    def create_window(self, *largs):
        # ensure the mouse is still not up after window creation, otherwise, we
        # have some weird bugs
        self.dispatch('on_mouse_up', 0, 0, 'all', [])

        # force display to show (available only for fullscreen)
        displayidx = Config.getint('graphics', 'display')
        if 'SDL_VIDEO_FULLSCREEN_HEAD' not in environ and displayidx != -1:
            environ['SDL_VIDEO_FULLSCREEN_HEAD'] = '%d' % displayidx

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

        # right now, activate resizable window only on linux.
        # on window / macosx, the opengl context is lost, and we need to
        # reconstruct everything. Check #168 for a state of the work.
        if platform in ('linux', 'macosx', 'win') and \
                Config.getboolean('graphics', 'resizable'):
            self.flags |= pygame.RESIZABLE

        try:
            pygame.display.init()
        except pygame.error as e:
            raise CoreCriticalException(e.message)

        multisamples = 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.set_caption(self.title)

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

        if self._fake_fullscreen:
            if not self.borderless:
                self.fullscreen = self._fake_fullscreen = False
            elif not self.fullscreen or self.fullscreen == 'auto':
                self.borderless = self._fake_fullscreen = False

        if self.fullscreen == 'fake':
            self.borderless = self._fake_fullscreen = True
            Logger.warning("The 'fake' fullscreen option has been "
                            "deprecated, use Window.borderless or the "
                            "borderless Config option instead.")

        if self.fullscreen == 'fake' or self.borderless:
            Logger.debug('WinPygame: Set window to borderless mode.')

            self.flags |= pygame.NOFRAME
            # If no position set in borderless mode, we always need
            # to set the position. So use 0, 0.
            if self._pos is None:
                self._pos = (0, 0)
            environ['SDL_VIDEO_WINDOW_POS'] = '%d,%d' % self._pos

        elif self.fullscreen in ('auto', True):
            Logger.debug('WinPygame: Set window to fullscreen mode')
            self.flags |= pygame.FULLSCREEN

        elif self._pos is not None:
            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(Config.get('kivy', 'keyboard_repeat_delay'))
        repeat_rate = float(Config.get('kivy', 'keyboard_repeat_rate'))
        pygame.key.set_repeat(repeat_delay, int(1000. / repeat_rate))

        # set window icon before calling set_mode
        try:
            filename_icon = self.icon or Config.get('kivy', 'window_icon')
            if filename_icon == '':
                logo_size = 32
                if platform == 'macosx':
                    logo_size = 512
                elif platform == 'win':
                    logo_size = 64
                filename_icon = 'kivy-icon-{}.png'.format(logo_size)
                filename_icon = resource_find(
                        join(kivy_data_dir, 'logo', filename_icon))
            self.set_icon(filename_icon)
        except:
            Logger.exception('Window: cannot set icon')

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

        if pygame.RESIZABLE & self.flags:
            self._pygame_set_mode()

        info = pygame.display.Info()
        self._size = (info.current_w, info.current_h)
        # self.dispatch('on_resize', *self._size)

        # in order to debug futur issue with pygame/display, let's show
        # more debug output.
        Logger.debug('Window: Display driver ' + pygame.display.get_driver())
        Logger.debug('Window: Actual window size: %dx%d',
                     info.current_w, info.current_h)
        if platform != 'android':
            # unsupported platform, such as android that doesn't support
            # gl_get_attribute.
            Logger.debug(
                'Window: Actual color bits r%d g%d b%d a%d',
                pygame.display.gl_get_attribute(pygame.GL_RED_SIZE),
                pygame.display.gl_get_attribute(pygame.GL_GREEN_SIZE),
                pygame.display.gl_get_attribute(pygame.GL_BLUE_SIZE),
                pygame.display.gl_get_attribute(pygame.GL_ALPHA_SIZE))
            Logger.debug(
                'Window: Actual depth bits: %d',
                pygame.display.gl_get_attribute(pygame.GL_DEPTH_SIZE))
            Logger.debug(
                'Window: Actual stencil bits: %d',
                pygame.display.gl_get_attribute(pygame.GL_STENCIL_SIZE))
            Logger.debug(
                'Window: Actual multisampling samples: %d',
                pygame.display.gl_get_attribute(pygame.GL_MULTISAMPLESAMPLES))
        super(WindowPygame, self).create_window()

        # set mouse visibility
        self._set_cursor_state(self.show_cursor)

        # if we are on android platform, automatically create hooks
        if android:
            from kivy.support import install_android
            install_android()
Пример #57
0
    def create_window(self, *largs):
        # ensure the mouse is still not up after window creation, otherwise, we
        # have some weird bugs
        self.dispatch('on_mouse_up', 0, 0, 'all', [])

        # force display to show (available only for fullscreen)
        displayidx = Config.getint('graphics', 'display')
        if not 'SDL_VIDEO_FULLSCREEN_HEAD' in environ and displayidx != -1:
            environ['SDL_VIDEO_FULLSCREEN_HEAD'] = '%d' % displayidx

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

        # right now, activate resizable window only on linux.
        # on window / macosx, the opengl context is lost, and we need to
        # reconstruct everything. Check #168 for a state of the work.
        if platform in ('linux', 'macosx', 'win') and \
                Config.getint('graphics', 'resizable'):
            self.flags |= pygame.RESIZABLE

        try:
            pygame.display.init()
        except pygame.error as e:
            raise CoreCriticalException(e.message)

        multisamples = 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.set_caption(self.title)

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

        if self.fullscreen == 'fake':
            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)
            environ['SDL_VIDEO_WINDOW_POS'] = '%d,%d' % self._pos

        elif self.fullscreen in ('auto', True):
            Logger.debug('WinPygame: Set window to fullscreen mode')
            self.flags |= pygame.FULLSCREEN

        elif self._pos is not None:
            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(Config.get('kivy', 'keyboard_repeat_delay'))
        repeat_rate = float(Config.get('kivy', 'keyboard_repeat_rate'))
        pygame.key.set_repeat(repeat_delay, int(1000. / repeat_rate))

        # set window icon before calling set_mode
        try:
            filename_icon = self.icon or Config.get('kivy', 'window_icon')
            if filename_icon == '':
                logo_size = 32
                if platform == 'macosx':
                    logo_size = 512
                elif platform == 'win':
                    logo_size = 64
                filename_icon = 'kivy-icon-{}.png'.format(logo_size)
                filename_icon = resource_find(
                        join(kivy_data_dir, 'logo', filename_icon))
            self.set_icon(filename_icon)
        except:
            Logger.exception('Window: cannot set icon')

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

        info = pygame.display.Info()
        self._size = (info.current_w, info.current_h)
        #self.dispatch('on_resize', *self._size)

        # in order to debug futur issue with pygame/display, let's show
        # more debug output.
        Logger.debug('Window: Display driver ' + pygame.display.get_driver())
        Logger.debug('Window: Actual window size: %dx%d',
                     info.current_w, info.current_h)
        if platform != 'android':
            # unsupported platform, such as android that doesn't support
            # gl_get_attribute.
            Logger.debug(
                'Window: Actual color bits r%d g%d b%d a%d',
                pygame.display.gl_get_attribute(pygame.GL_RED_SIZE),
                pygame.display.gl_get_attribute(pygame.GL_GREEN_SIZE),
                pygame.display.gl_get_attribute(pygame.GL_BLUE_SIZE),
                pygame.display.gl_get_attribute(pygame.GL_ALPHA_SIZE))
            Logger.debug(
                'Window: Actual depth bits: %d',
                pygame.display.gl_get_attribute(pygame.GL_DEPTH_SIZE))
            Logger.debug(
                'Window: Actual stencil bits: %d',
                pygame.display.gl_get_attribute(pygame.GL_STENCIL_SIZE))
            Logger.debug(
                'Window: Actual multisampling samples: %d',
                pygame.display.gl_get_attribute(pygame.GL_MULTISAMPLESAMPLES))
        super(WindowPygame, self).create_window()

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

        # if we are on android platform, automaticly create hooks
        if android:
            from kivy.support import install_android
            install_android()
Пример #58
0
from kivy.uix.popup import Popup
from kivy.uix.screenmanager import ScreenManager
from kivy.uix.textinput import TextInput
from subprocess import Popen, PIPE
from waeup.identifier.config import (
    get_json_settings, get_default_settings, get_conffile_location,
)
from waeup.identifier.webservice import (
    store_fingerprint, get_url, get_fingerprints,
)


# Enable virtualkeyboard
if Config is not None:
    # when building sphinx docs, `Config` is None. How come?
    if not Config.get('kivy', 'keyboard_mode'):
        Config.set('kivy', 'keyboard_mode', 'systemandmulti')

#: The set of chars allowed in filenames we handle.
#: Last char must not be slash.
VALID_FILENAME = re.compile('^[a-zA-Z0-9/\._\-]+$')

#: A valid student id looks like this
#: Two or three uppercase ASCIIs followed by at least five digits
RE_STUDENT_ID = re.compile('^[A-Z]{1,3}[0-9]{5,}$')


#: How often do we look for new data while executing commands?
POLL_INTERVAL = 0.1

Пример #59
0
from kivy.config import Config

Config.set('graphics', 'shaped', 1)

from kivy.resources import resource_find

default_shape = Config.get('kivy', 'window_shape')
alpha_shape = resource_find('data/logo/kivy-icon-512.png')

from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import (
    BooleanProperty,
    StringProperty,
    ListProperty,
)

Builder.load_string('''
#:import win kivy.core.window.Window
<Root>:
    orientation: 'vertical'
    BoxLayout:
        Button:
            text: 'default_shape'
            on_release: app.shape_image = app.default_shape
        Button:
            text: 'alpha_shape'
            on_release: app.shape_image = app.alpha_shape
    BoxLayout:
Пример #60
0
    '''
    @wraps(func)
    def delayed_func(*args, **kwargs):
        def callback_func(dt):
            func(*args, **kwargs)

        Clock.schedule_once(callback_func, 0)

    return delayed_func


if 'KIVY_DOC_INCLUDE' in environ:
    #: Instance of :class:`ClockBaseBehavior`.
    Clock = None
else:
    _classes = {
        'default': ClockBase,
        'interrupt': ClockBaseInterrupt,
        'free_all': ClockBaseFreeInterruptAll,
        'free_only': ClockBaseFreeInterruptOnly
    }
    _clk = environ.get('KIVY_CLOCK', Config.get('kivy', 'kivy_clock'))
    if _clk not in _classes:
        raise Exception(
            '{} is not a valid kivy clock. Valid clocks are {}'.format(
                _clk, sorted(_classes.keys())))

    Clock = register_context('Clock', _classes[_clk])
    '''The kivy Clock instance. See module documentation for details.
    '''