Пример #1
0
 def on_focus(self, instance, value, *largs):
     win = self._win
     if not win:
         self._win = win = self.get_root_window()
     if not win:
         # we got argument, it could be the previous schedule
         # cancel focus.
         if len(largs):
             Logger.warning('Textinput: '
                 'Cannot focus the element, unable to get root window')
             return
         else:
             Clock.schedule_once(partial(self.on_focus, self, value), 0)
         return
     if value:
         keyboard = win.request_keyboard(self._keyboard_released, self)
         self._keyboard = keyboard
         keyboard.bind(
             on_key_down=self._keyboard_on_key_down,
             on_key_up=self._keyboard_on_key_up)
         Clock.schedule_interval(self._do_blink_cursor, 1 / 2.)
     else:
         keyboard = self._keyboard
         keyboard.unbind(
             on_key_down=self._keyboard_on_key_down,
             on_key_up=self._keyboard_on_key_up)
         keyboard.release()
         self.cancel_selection()
         Clock.unschedule(self._do_blink_cursor)
         self._win = None
Пример #2
0
    def core_select_lib(category, llist, create_instance=False):
        category = category.lower()
        for option, modulename, classname in llist:
            try:
                # module activated in config ?
                if option not in kivy.kivy_options[category]:
                    Logger.debug('%s: option <%s> ignored by config' %
                        (category.capitalize(), option))
                    continue

                # import module
                mod = __import__(name='%s.%s' % (category, modulename),
                                 globals=globals(),
                                 locals=locals(),
                                 fromlist=[modulename], level=-1)
                cls = mod.__getattribute__(classname)

                # ok !
                Logger.info('%s: using <%s> as %s provider' %
                    (category.capitalize(), option, category))
                if create_instance:
                    cls = cls()
                return cls

            except Exception as e:
                Logger.warning('%s: Unable to use <%s> as %s'
                     'provider' % (category.capitalize(), option, category))
                Logger.debug('', exc_info = e)

        Logger.critical('%s: Unable to find any valuable %s provider '
              'at all!' % (category.capitalize(), category.capitalize()))
Пример #3
0
    def run(self):
        self.haveSocket = False
        # create socket
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # fix trouble if python leave without cleaning well the socket
        # not needed under windows, he can reuse addr even if the socket
        # are in fin2 or wait state.
        if os.name in ['posix', 'mac'] and hasattr(socket, 'SO_REUSEADDR'):
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # try to bind the socket, retry if necessary
        while not self.haveSocket and self.isRunning:
            try :
                self.socket.bind((self.ipAddr, self.port))
                self.socket.settimeout(0.5)
                self.haveSocket = True

            except socket.error, e:
                error, message = e.args

                # special handle for EADDRINUSE
                if error == errno.EADDRINUSE:
                    Logger.error('OSC: Address %s:%i already in use, retry in 2 second' % (self.ipAddr, self.port))
                else:
                    Logger.exception(e)
                self.haveSocket = False

                # sleep 2 second before retry
                time.sleep(2)
Пример #4
0
    def on_play(self, instance, value):
        if not value:
            Logger.info('Recorder: Stop playing %r' % self.filename)
            EventLoop.remove_input_provider(self)
            return
        if not exists(self.filename):
            Logger.error('Recorder: Unable to found %r file, play aborted.' % (
                self.filename))
            return

        with open(self.filename, 'r') as fd:
            data = fd.read().splitlines()

        if len(data) < 2:
            Logger.error('Recorder: Unable to play %r, file truncated.' % (
                self.filename))
            return

        if data[0] != '#RECORDER1.0':
            Logger.error('Recorder: Unable to play %r, invalid header.' % (
                self.filename))
            return

        # decompile data
        self.play_data = [literal_eval(x) for x in data[1:]]
        self.play_time = time()
        self.play_me = {}
        Logger.info('Recorder: Start playing %d events from %r' %
                (len(self.play_data), self.filename))
        EventLoop.add_input_provider(self)
Пример #5
0
def resource_add_path(path):
    '''Add a custom path to search in
    '''
    if path in resource_paths:
        return
    Logger.debug('Resource: add <%s> in path list' % path)
    resource_paths.append(path)
Пример #6
0
 def read_from_in_pipe(self, *l):
     txt = '\n'
     txt_line = ''
     os_read = os.read
     self_stdin_pipe = self.stdin_pipe
     self_mode = self.mode
     self_write = self.write
     Clock_schedule_once = Clock.schedule_once
     self_update_cache = self.update_cache
     self_flush = self.flush
     obj = self.obj
     try:
         while txt != '':
             txt = os_read(self_stdin_pipe, 1)
             txt_line = u''.join((txt_line, txt))
             if txt == '\n':
                 if self_mode == 'stdin':
                     # run command
                     self_write(txt_line)
                 else:
                     Clock_schedule_once(
                         partial(self_update_cache, txt_line, obj), 0)
                     self_flush()
                 txt_line = ''
     except OSError as e:
         Logger.exception(e)
Пример #7
0
 def delete_clock(self, touch, *args):
     # TODO: Fix touch_up passing through when popup dismissed.
     try:
         Clock.unschedule(touch.ud['event'])
     except KeyError:
         Logger.exception(
             'Application: Touch up passed through and unscheduled clock event could not be unscheduled. A bug...')
Пример #8
0
 def pool_updated(self):
     """
         Called when the expense pool has been updated
     """
     Logger.debug("Ndf Pool : pool updated")
     self.settings.set('main', 'expenses', self.pool.stored_version())
     self.property('pool').dispatch(self)
Пример #9
0
    def do_pause(self):
        # should go to app pause mode.
        from kivy.app import App
        from kivy.base import stopTouchApp
        app = App.get_running_app()
        if not app:
            Logger.info('WindowSDL: No running App found, exit.')
            stopTouchApp()
            return

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

        # XXX FIXME wait for sdl resume
        while True:
            event = self._win.poll()
            if event is False:
                continue
            if event is None:
                continue

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

        app.dispatch('on_resume')
Пример #10
0
 def on_key_up(self, key,
     scancode=None, codepoint=None, modifier=None, **kwargs):
     '''Event called when a key is up (same arguments as on_keyboard)'''
     if 'unicode' in kwargs:
         Logger.warning("The use of the unicode parameter is deprecated, "
             "and will be removed in future versions. Use codepoint "
             "instead, which has identical semantics.")
Пример #11
0
 def check_auth(self):
     """
         Launch an authentication check
     """
     Logger.info("Ndf : Checking auth : NDFAPP")
     _connection = self.get_connection()
     _connection.check_auth(self.check_auth_success, self.check_auth_error)
Пример #12
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'])
Пример #13
0
    def on_touch_down(self, touch):
        if super(HexMapCell, self).on_touch_down(touch):
            return False

        coord_x, coord_y = self.even_r_coords
        if not self.visible_on_map:
            return False

        with self.canvas.after:
            Color(*kivy.utils.get_color_from_hex('#000000'))
            radius = 2 * self.height
            self.ell = Line(circle=(self.x, self.y, radius, 0, 360, 6), width=2)

        if not self.collide_with_bounding_circle(touch.x, touch.y):
            return False

        Logger.debug('Selected: ({}, {})'.format(coord_x, coord_y))
        with self.canvas.after:
            if 'button' in touch.profile and touch.button == 'left':
                Color(*kivy.utils.get_color_from_hex('#00FF00'))

            if 'button' in touch.profile and touch.button == 'right':
                # TODO Will refactor to have separate on_touch_up for selected target hex instead.
                Color(*kivy.utils.get_color_from_hex('#FF0000'))
            radius = 2 * self.height
            self.ell = Line(circle=(self.x, self.y, radius, 0, 360, 6), width=2)

        self.parent.game.update_selected_cell(self.even_r_coords, self.terrain_colour)
        return True
Пример #14
0
 def ensure_window(self):
     '''Ensure that we have a window.
     '''
     import kivy.core.window  # NOQA
     if not self.window:
         Logger.critical('App: Unable to get a Window, abort.')
         sys.exit(1)
Пример #15
0
 def _initialize_image(self, step=-1):
     if step == -1:
         step = self.idx_stp
     try:
         if self.seq_images[step] == "":
             #Logger.debug("_initialize_image: same image for background:{}".format(self.bg_img))
             pass
         else:
             Logger.debug("{}-{}".format(self.base_seq_dir, self.seq_images[step]))
             file_name = ""
             if os.path.exists(os.path.join("..", self.seq_images[step])):
                 file_name = self.seq_images[step]
             elif os.path.exists(os.path.join(self.base_seq_dir, self.seq_images[step])):
                 file_name = os.path.join(self.base_seq_dir, self.seq_images[step])
             Logger.debug("_initialize_image: Initializing {}".format(file_name))
             if not file_name == "":
                 self.bg_img = file_name
                 Logger.debug("_initialize_image: new image for background:{}".format(file_name))
             else:
                 self.bg_img = self.default_bg_img
                 Logger.debug("_initialize_image: error ({}) and then default for bg:{}".format(
                     file_name, self.default_bg_img))
     except IndexError:
         self.bg_img = self.default_bg_img
         Logger.debug("_initialize_image: IndexError. Default for bg:{}".format(
             self.default_bg_img))
Пример #16
0
    def on_start(self):
        ''' This is the start point of the kivy ui
        '''
        import time
        Logger.info('Time to on_start: {} <<<<<<<<'.format(time.clock()))
        Logger.info("dpi: {} {}".format(metrics.dpi, metrics.dpi_rounded))
        win = Window
        win.bind(size=self.on_size,
                    on_keyboard=self.on_keyboard)
        win.bind(on_key_down=self.on_key_down)

        # Register fonts without this you won't be able to use bold/italic...
        # inside markup.
        from kivy.core.text import Label
        Label.register('Roboto',
                   'gui/kivy/data/fonts/Roboto.ttf',
                   'gui/kivy/data/fonts/Roboto.ttf',
                   'gui/kivy/data/fonts/Roboto-Bold.ttf',
                   'gui/kivy/data/fonts/Roboto-Bold.ttf')

        win.softinput_mode = 'below_target'
        self.on_size(win, win.size)
        self.init_ui()
        self.load_wallet_by_name(self.electrum_config.get_wallet_path())
        # init plugins
        run_hook('init_kivy', self)
        # were we sent a url?
        self.uri = self.electrum_config.get('url')
        # default tab
        self.switch_to('send' if self.uri else 'history')
Пример #17
0
    def on_start(self):
        ''' This is the start point of the kivy ui
        '''
        import time
        Logger.info('Time to on_start: {} <<<<<<<<'.format(time.clock()))
        Logger.info("dpi: {} {}".format(metrics.dpi, metrics.dpi_rounded))
        win = Window
        win.bind(size=self.on_size, on_keyboard=self.on_keyboard)
        win.bind(on_key_down=self.on_key_down)
        win.softinput_mode = 'below_target'
        self.on_size(win, win.size)
        self.init_ui()
        self.load_wallet_by_name(self.electrum_config.get_wallet_path())
        # init plugins
        run_hook('init_kivy', self)
        # default tab
        self.switch_to('history')
        # bind intent for bitcoin: URI scheme
        if platform == 'android':
            from android import activity
            from jnius import autoclass
            PythonActivity = autoclass('org.renpy.android.PythonActivity')
            mactivity = PythonActivity.mActivity
            self.on_new_intent(mactivity.getIntent())
            activity.bind(on_new_intent=self.on_new_intent)

        # URI passed in config
        uri = self.electrum_config.get('url')
        if uri:
            self.set_URI(uri)
Пример #18
0
    def config_updated(self, config):

        self.wifi_config = config.wifi_config
        Logger.debug("WifiConfig: got config: {}".format(self.wifi_config.to_json()))

        wifi_switch = self.ids.wifi_enabled
        wifi_switch.setControl(SettingsSwitch(active=self.wifi_config.active))
        wifi_switch.control.bind(active=self.on_wifi_enable_change)

        wifi_client_switch = self.ids.client_mode
        wifi_client_switch.setControl(SettingsSwitch(active=self.wifi_config.client_mode_active))
        wifi_client_switch.control.bind(active=self.on_client_mode_enable_change)

        wifi_ap_switch = self.ids.ap_mode
        wifi_ap_switch.setControl(SettingsSwitch(active=self.wifi_config.ap_mode_active))
        wifi_ap_switch.control.bind(active=self.on_ap_mode_enable_change)

        ap_encryption = self.ids.ap_encryption
        ap_encryption.bind(on_setting=self.on_ap_encryption)
        encryption_spinner = SettingsMappedSpinner()
        self.load_ap_encryption_spinner(encryption_spinner, self.wifi_config.ap_encryption)
        ap_encryption.setControl(encryption_spinner)

        ap_channel = self.ids.ap_channel
        channel_spinner = SettingsMappedSpinner()
        self.build_ap_channel_spinner(channel_spinner, str(self.wifi_config.ap_channel))
        ap_channel.bind(on_setting=self.on_ap_channel)
        ap_channel.setControl(channel_spinner)

        self.ids.client_ssid.text = self.wifi_config.client_ssid
        self.ids.client_password.text = self.wifi_config.client_password

        self.ids.ap_ssid.text = self.wifi_config.ap_ssid
        self.ids.ap_password.text = self.wifi_config.ap_password
Пример #19
0
def CreateAtlas(oPicPath,oAtlasFile,uDebugMsg):
    ''' creates an atlas file from all picture files in a folder '''

    if oORCA.bIgnoreAtlas:
        return

    #can\'t get JPEG lib included in package, so just ignore atlas
    #if oORCA.uPlatform=='macosx'  or oORCA.uPlatform=="ios" or oORCA.uPlatform=="win":
    if oORCA.uPlatform=='macosx'  or oORCA.uPlatform=="ios":
        return

    try:
        if not FileExists(oAtlasFile):
            Logger.debug(uDebugMsg)
            #aExtensions=[u'.png',u'.jpg',u'.bmp',u'.gif']
            # we exclude gifs as they might be animated
            aExtensions=[u'.png',u'.jpg',u'.bmp']
            aPicFiles=[]

            oDirList=GetFileList(oPicPath, bSubDirs=True,bFullPath=True)
            for uFileName in oDirList:
                uExtension = os.path.splitext(uFileName)[1].lower()
                if uExtension in aExtensions:
                    if uFileName.find( AdjustPathToOs(oORCA.uSkinPath+u'/atlas/'))==-1:
                        aPicFiles.append(uFileName)
            try:
                Atlas.create(oAtlasFile[:-6],aPicFiles,1024)
            except Exception:
                pass
    except Exception as e:
        LogError(u'Error creating Atlas File:',e)
Пример #20
0
  def tile_draw(self, nx, ny, tx, ty, sx, sy, zoom, bound):
        '''Draw a specific tile on the screen.
        Return False if the tile is not yet available.'''
        # nx, ny = index of tile
        # tx, ty = real position on scatter
        # sx, sy = real size on scatter
        # pzoom = current zoom level
        image = self.tileserver.get(nx, bound-ny-1, zoom, self.maptype)
        if image in (None, False):
            return

        if not image.texture:
          Logger.exception('Returned image has no texture.')
          return
        if image.texture.wrap is None:
          image.texture.wrap = GL_CLAMP

        alpha = Cache.get('tileserver.tilesalpha', image.id)
        if alpha is None:
          alpha = 0
        if image.loaded:          # as soon as we have the image
          alpha += min(self._dt * 4, 1.0)  # fade it in
        Cache.append('tileserver.tilesalpha', image.id, alpha)

        with self.canvas:
          Color(1, 1, 1, alpha)
          Rectangle(pos=(tx, ty), size=(sx, sy), texture=image.texture)
Пример #21
0
    def build(self):

        # the root is created in pictures.kv
        root = self.root

        # get any files into images directory
        curdir = dirname(__file__)
        ## for filename in glob(join(curdir, 'images', '*')):
        #try:
        #    # load the image
        #    URL = 'https://farm1.staticflickr.com/176/478156552_9badc190eb_o.jpg'
        #    img =  AsyncImage(source=URL)
        #    #picture = Picture(source=filename, rotation=randint(-30, 30))
        #    # add to the main field
        #    #root.add_widget(picture)
        #    root.add_widget(img)
        #except Exception as e:
        #    Logger.exception('Pictures: Unable to load <%s>' % filename)    
        
        for filename in glob(join(curdir, 'images', '*')):
            try:
                # load the image
                picture = Picture(source=filename, rotation=randint(-30, 30))
                # add to the main field
                root.add_widget(picture)
            except Exception as e:
                Logger.exception('Pictures: Unable to load <%s>' % filename)
Пример #22
0
        def calculate_break_point(forces,material):

            materials = {13: 20.4, 16: 30.6, 18:38.5, 19:42.9, 22:57.2,25.4:75.8, 26:79.3 , 28:91.6, 30:105, 32:119 }
            ton = 2000

            try:
                for force in forces:
                    if abs(float(forces[0])) > materials[float(material)] * ton:
                        print "BREAKS"

                        print "\nMax tension to break:"
                        print materials[float(material)] * ton

                        print " \nCurrent tension:"
                        print abs(float(forces[0]))

                        pass_image.source = 'breaks.jpg'
                        pass_image.reload()
			
                    else:
                        print "PASS"

                        print "\nMax tension to break:"
                        print materials[float(material)] * ton

                        print " \nCurrent tension:"
                        print abs(float(forces[0]))
                        pass_image.source = 'pass.jpg'
                        pass_image.reload()
		
            except Exception as e:
                Logger.exception('Material does not exist')
    def read(self, keep_reading):
        """
        Reads data from the socket. Will continue to read until either "\r\n" is found in the data read from the
        socket or keep_reading.is_set() returns false
        :param keep_reading: Event object that is checked while data is read
        :type keep_reading: threading.Event
        :return: String or None
        """
        msg = ''
        Logger.info("SocketConnection: reading...")

        while keep_reading.is_set():
            try:
                data = self.socket.recv(4096)
                if data == '':
                    return None

                msg += data

                if msg[-2:] == '\r\n':
                    if msg != '':
                        Logger.info("SocketConnection: returning data {}".format(msg))
                        return msg
                    else:
                        return None
            except socket.timeout:
                pass
Пример #24
0
    def _add_unselected_channels(self, channels, source_ref):
        ProgressSpinner.increment_refcount()
        def get_results(results):
            # Auto-switch to time mode in charts only if the user
            # did not request it.
            if (
                    self.line_chart_mode == LineChartMode.DISTANCE and
                    not self._results_has_distance(results)
                ):
                    if self._user_refresh_requested == True:
                        toast("Warning: one or more selected laps have missing distance data", length_long=True)
                        self._user_refresh_requested = False
                    else:
                        self.line_chart_mode = LineChartMode.TIME
                        self._refresh_chart_mode_toggle()

            # clone the incoming list of channels and pass it to the handler
            if self.line_chart_mode == LineChartMode.TIME:
                Clock.schedule_once(lambda dt: self._add_channels_results_time(channels[:], results))
            elif self.line_chart_mode == LineChartMode.DISTANCE:
                Clock.schedule_once(lambda dt: self._add_channels_results_distance(channels[:], results))
            else:
                Logger.error('LineChart: Unknown line chart mode ' + str(self.line_chart_mode))
        try:
            self.datastore.get_channel_data(source_ref, ['Interval', 'Distance'] + channels, get_results)
        except Exception as e:
            Logger.warn('Non existant channel selected, not loading channels {}; {}'.format(channels, e))
        finally:
            ProgressSpinner.decrement_refcount()
Пример #25
0
 def stop(self):
     self._running.clear()
     try:
         if self._status_thread:
             self._status_thread.join()
     except Exception as e:
         Logger.warn('StatusPump: failed to join status_worker: {}'.format(e))
Пример #26
0
    def __init__(self, **kwargs):
        kwargs.setdefault('filename', None)
        kwargs.setdefault('eos', 'stop')
        kwargs.setdefault('async', True)
        kwargs.setdefault('autoplay', False)

        super(VideoBase, self).__init__()

        self._wantplay = False
        self._buffer = None
        self._filename = None
        self._texture = None
        self._volume = 1.
        self._state = ''

        self._autoplay = kwargs.get('autoplay')
        self._async = kwargs.get('async')
        self.eos = kwargs.get('eos')
        if self.eos == 'pause':
            Logger.warning("'pause' is deprecated. Use 'stop' instead.")
            self.eos = 'stop'
        self.filename = kwargs.get('filename')

        Clock.schedule_interval(self._update, 1 / 30.)

        if self._autoplay:
            self.play()
Пример #27
0
 def log_mesg(self, mesg="you forgot something..."):
     """For log messages.
     
     Arguments:
     - `mesg`: The debug message.
     """
     Logger.debug("DiceKV: " + mesg)
Пример #28
0
    def run(self):
        '''Launches the app in standalone mode.
        '''
        if not self.built:
            self.load_config()
            self.load_kv(filename=self.kv_file)
            root = self.build()
            if root:
                self.root = root
        if self.root:
            if not isinstance(self.root, Widget):
                Logger.critical('App.root must be an _instance_ of Widget')
                raise Exception('Invalid instance in App.root')
            from kivy.core.window import Window
            Window.add_widget(self.root)

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

        self.dispatch('on_start')
        runTouchApp()
        self.stop()
Пример #29
0
    def populate(self):
        self._textures = []
        fname = self.filename
        if __debug__:
            Logger.trace('Image: %r, populate to textures (%d)' %
                         (fname, len(self._data)))

        for count in range(len(self._data)):

            # first, check if a texture with the same name already exist in the
            # cache
            chr = type(fname)
            uid = chr(u'%s|%d|%d') % (fname, self._mipmap, count)
            texture = Cache.get('kv.texture', uid)

            # if not create it and append to the cache
            if texture is None:
                imagedata = self._data[count]
                source = '{}{}|'.format(
                    'zip|' if fname.endswith('.zip') else '',
                    self._nocache)
                imagedata.source = chr(source) + uid
                texture = Texture.create_from_data(
                    imagedata, mipmap=self._mipmap)
                if not self._nocache:
                    Cache.append('kv.texture', uid, texture)
                if imagedata.flip_vertical:
                    texture.flip_vertical()

            # set as our current texture
            self._textures.append(texture)

            # release data if ask
            if not self.keep_data:
                self._data[count].release_data()
Пример #30
0
    def recover_connection(self):
        if self._disconnect_callback:
            self._disconnect_callback()

        if self._enable_autodetect.is_set():
            Logger.debug("RCPAPI: attempting to recover connection")
            self.run_auto_detect()