Пример #1
0
    def __LoadXmlFile(self,uFile,uTarget):
        ''' Loads all strings for the language from a specific files'''
        if not FileExists(uFile):
            Logger.warning (u'Language: String File does not exist:'+uFile)
            return
        if uFile in self.aLoadedFiles:
            Logger.debug (u'Language: Skip duplicate language file loading:'+uFile)

        self.aLoadedFiles.append(uFile)

        try:
            oET_Root = ElementTree(file=uFile).getroot()
            for oXMLString in oET_Root.findall('string'):
                uText=oXMLString.text
                if uText is None:
                    uText=u''
                uText  = ToUnicode(uText)
                sIndex = GetXMLTextAttribut(oXMLString,u'id',True,0)
                uTarget[sIndex]  = uText

        except ParseError as e:
            uMsg=LogError(u'Language: Fatal Error:Load Language XmlFile (xml parse error):',e)
            ShowErrorPopUp(uTitle='Fatal Error',uMessage=uMsg, bAbort=True)
        except Exception as e:
            uMsg=LogError(u'Language: Fatal Error:Load Language XmlFile (2):',e)
            ShowErrorPopUp(uTitle='Fatal Error',uMessage=uMsg, bAbort=True)
Пример #2
0
    def load(self, filename):
        try:
            try:
                im = pygame.image.load(filename)
            except UnicodeEncodeError:
                im = pygame.image.load(filename.encode('utf8'))
        except:
            Logger.warning('Image: Unable to load image <%s>' % filename)
            raise

        fmt = ''
        if im.get_bytesize() == 3:
            fmt = 'rgb'
        elif im.get_bytesize() == 4:
            fmt = 'rgba'

        # image loader work only with rgb/rgba image
        if fmt not in ('rgb', 'rgba'):
            try:
                imc = im.convert(32)
                fmt = 'rgba'
            except:
                Logger.warning(
                    'Image: Unable to convert image <%s> to rgba (was %s)' %
                    filename, im.fmt)
                raise
            im = imc

        # update internals
        self.filename = filename
        data = pygame.image.tostring(im, fmt.upper(), True)
        return [ImageData(im.get_width(), im.get_height(), fmt, data)]
Пример #3
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()))
Пример #4
0
    def FindWidget(self,oScreenPage,uWidgetName,bDoNotCreatePage=False):
        ''' Finds a widget with a given name '''
        uWidgetNameRep=ReplaceVars(uWidgetName)
        if oScreenPage is None:
            oScreenPage=self.oCurrentPage

        if oScreenPage is None:
            uMsg=u'The Screen: Page for Widget not found:'+uWidgetNameRep
            Logger.error (uMsg)
            return None

        oWidget = oScreenPage.aWidgets.get(uWidgetNameRep)
        if not oWidget is None:
            if not oScreenPage.bIsInit and not bDoNotCreatePage:
                oScreenPage.Create()
            return oWidget
        Logger.warning ("Can't find widget [%s] on current page [%s], looking on all pages" % (uWidgetName,oScreenPage.uPageName))

        for oPageName in self.lPages:
            oPage=self.lPages[oPageName]
            oWidget = oPage.aWidgets.get(uWidgetNameRep)
            if not oWidget is None:
                if not oPage.bIsInit and not bDoNotCreatePage:
                    oPage.Create()
                return oWidget

        uMsg=u'The Screen: Widget not found:'+uWidgetNameRep
        Logger.error (uMsg)

        return None
Пример #5
0
def _on_gstplayer_message(mtype, message):
    if mtype == "error":
        Logger.error("AudioGstplayer: {}".format(message))
    elif mtype == "warning":
        Logger.warning("AudioGstplayer: {}".format(message))
    elif mtype == "info":
        Logger.info("AudioGstplayer: {}".format(message))
Пример #6
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'])
Пример #7
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()
Пример #8
0
    def protocol_line_received(self, line):
        Logger.info("Line received: {}".format(line))

        header = line[:2]
        body = line[3:]

        if header == 'DL':
            self.save_available_endpoints(body)
            if self.enpoint_is_connected:
                pass
            else:
                self.endpoint_connecting_process()

        elif header == 'CD':
            if body == 'OK':
                self.enpoint_is_connected = True
                self.utility_lt.reset()
                self.con_widget.update_status('GREEN', self.selected_device)
            else:
                self.on_device_disconnected()

        elif header == 'DD':
            self.on_device_disconnected()
        elif header == 'RE':
            self.endpoint_request_received(body)
        elif header == 'SE':
            #@TODO
            #handle error
            Logger.warning("SERVER ERROR: {}".format(body))
            pass
        else:
            #@TODO
            #handle undefined command
            Logger.warning("UNDEFINED COMMAND: {}".format(body))
            pass
Пример #9
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.")
Пример #10
0
    def open(self, *largs, **kwargs):
        '''Show the view window from the :attr:`attach_to` widget. If set, it
        will attach to the nearest window. If the widget is not attached to any
        window, the view will attach to the global
        :class:`~kivy.core.window.Window`.

        When the view is opened, it will be faded in with an animation. If you
        don't want the animation, use::

            view.open(animation=False)

        '''
        if self._window is not None:
            Logger.warning('ModalView: you can only open once.')
            return
        # search window
        self._window = self._search_window()
        if not self._window:
            Logger.warning('ModalView: cannot open view, no window found.')
            return
        self._window.add_widget(self)
        self._window.bind(
            on_resize=self._align_center,
            on_keyboard=self._handle_keyboard)
        self.center = self._window.center
        self.fbind('center', self._align_center)
        self.fbind('size', self._align_center)
        if kwargs.get('animation', True):
            a = Animation(_anim_alpha=1., d=self._anim_duration)
            a.bind(on_complete=lambda *x: self.dispatch('on_open'))
            a.start(self)
        else:
            self._anim_alpha = 1.
            self.dispatch('on_open')
Пример #11
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
Пример #12
0
    def load(self, filename):
        Logger.debug("Image: Load <%s>" % filename)
        try:
            im = pygame.image.load(filename)
        except:
            Logger.warning("Image: Unable to load image <%s>" % filename)
            raise

        fmt = ""
        if im.get_bytesize() == 3:
            fmt = "rgb"
        elif im.get_bytesize() == 4:
            fmt = "rgba"

        # image loader work only with rgb/rgba image
        if fmt not in ("rgb", "rgba"):
            try:
                imc = im.convert(32)
                fmt = "rgba"
            except:
                Logger.warning("Image: Unable to convert image <%s> to rgba (was %s)" % filename, im.fmt)
                raise
            im = imc

        # update internals
        self.filename = filename
        data = pygame.image.tostring(im, fmt.upper(), True)
        return ImageData(im.get_width(), im.get_height(), fmt, data)
Пример #13
0
    def DoAction(self,oOrgAction):
        
        oAction=copy(oOrgAction)
        iRet=1
        oSetting,oCodesetCode=self.Helper_DoAction_GetCodesetCode(oAction)
        if oCodesetCode==None:
            return self.iLastRet

        # If cmd==* we pass the original action string

        uCmd=oCodesetCode.uCmd
        
        if uCmd==u'*':
            uCmd=oAction.aActionPars['commandname']
       
        # call the function to pass string to eventghost
        if oCodesetCode.uType==u'command':
            iRet=self.SendCommand(oCodesetCode,oSetting,u'c')
        if oCodesetCode.uType==u'event':
            iRet=self.SendCommand(oCodesetCode,oSetting,u'e'+oSetting.aInterFaceIniSettings.uPreFix)
        elif oCodesetCode.uType==u'key':
            iRet=self.SendCommand(oCodesetCode,oSetting,u'k')
        elif oCodesetCode.uType==u'macro':
            iRet=self.SendCommand(oCodesetCode,oSetting,u'a')
        elif oCodesetCode.uType==u'mouse':
            iRet=self.SendCommand(oCodesetCode,oSetting,u'm')
        else:
            Logger.warning (u'Invalid type: '+oCodesetCode.uType,oAction.sConfigName)
            iRet=1
        self.iLastRet=iRet
        return iRet
Пример #14
0
    def load(self, filename):
        Logger.debug('Image: Load <%s>' % filename)
        try:
            im = Image.open(filename)
        except:
            Logger.warning('Image: Unable to load image <%s>' % filename)
            raise

        # image loader work only with rgb/rgba image
        if im.mode.lower() not in ('rgb', 'rgba'):
            try:
                imc = im.convert('RGBA')
            except:
                Logger.warning(
                    'Image: Unable to convert image <%s> to rgba (was %s)' %
                    (filename, im.mode.lower()))
                raise
            im = imc

        # image are not in the good direction, flip !
        im = im.transpose(Image.FLIP_TOP_BOTTOM)

        # update internals
        self.filename = filename

        return ImageData(im.size[0], im.size[1],
            im.mode.lower(), im.tostring())
Пример #15
0
    def load(self, filename):
        try:
            loader = ffImageLoader(filename)
        except:
            Logger.warning('Image: Unable to load image <%s>' % filename)
            raise

        # update internals
        self.filename = filename
        images = []

        while True:
            frame, t = loader.next_frame()
            if frame is None:
                break
            images.append(frame)
        if not len(images):
            raise Exception('No image found in {}'.format(filename))

        w, h = images[0].get_size()
        ifmt = images[0].get_pixel_format()
        if ifmt != 'rgba' and ifmt != 'rgb24':
            fmt = 'rgba'
            sws = SWScale(w, h, ifmt, ofmt=fmt)
            for i, image in enumerate(images):
                images[i] = sws.scale(image)
        else:
            fmt = ifmt if ifmt == 'rgba' else 'rgb'

        return [ImageData(w, h, fmt, img.to_memoryview()[0], source_image=img)
                for img in images]
Пример #16
0
    def append(category, key, obj, timeout=None):
        '''Add a new object to the cache.

        :Parameters:
            `category`: str
                Identifier of the category.
            `key`: str
                Unique identifier of the object to store.
            `obj`: object
                Object to store in cache.
            `timeout`: double (optional)
                Time after which to delete the object if it has not been used.
                If None, no timeout is applied.
        '''
        #check whether obj should not be cached first
        if getattr(obj, '_no_cache', False):
            return
        try:
            cat = Cache._categories[category]
        except KeyError:
            Logger.warning('Cache: category <%s> not exist' % category)
            return
        timeout = timeout or cat['timeout']
        # FIXME: activate purge when limit is hit
        #limit = cat['limit']
        #if limit is not None and len(Cache._objects[category]) >= limit:
        #    Cache._purge_oldest(category)
        Cache._objects[category][key] = {
            'object': obj,
            'timeout': timeout,
            'lastaccess': Clock.get_time(),
            'timestamp': Clock.get_time()}
Пример #17
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()'''
        import urllib2
        proto = filename.split(':', 1)[0]
        if proto == 'smb':
            try:
                # note: it's important to load SMBHandler every time
                # otherwise the data is occasionaly 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 = ''
            suffix = '.%s' % (filename.split('.')[-1])
            _out_osfd, _out_filename = tempfile.mkstemp(
                    prefix='kivyloader', suffix=suffix)

            if proto == 'smb':
                # read from samba shares
                fd = urllib2.build_opener(SMBHandler).open(filename)
            else:
                # read from internet
                fd = urllib2.urlopen(filename)
            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:
            Logger.exception('Failed to load image <%s>' % filename)
            # close file when remote file not found or download error
            try:
                close(_out_osfd)
            except OSError:
                pass
            return self.error_image
        finally:
            if fd:
                fd.close()
            if _out_osfd:
                close(_out_osfd)
            if _out_filename != '':
                unlink(_out_filename)

        return data
Пример #18
0
 def stop(self):
     self._running.clear()
     try:
         if self._sample_thread is not None:
             self._sample_thread.join()
     except Exception as e:
         Logger.warning('DataBusPump: Failed to join sample_worker: {}'.format(e))
Пример #19
0
	def on_flash_mode(self, instance, value):
		if self.camera and self.params:
			if value not in self._flash_mode_to_android:
				Logger.warning('CameraPreview: flash mode `%s` not supported' % value)
				return
			self.params.setFlashMode(self._flash_mode_to_android[value])
			self.camera.setParameters(self.params)
Пример #20
0
 def loadCurrentTracks(self, progressCallback=None, winCallback=None, failCallback=None):
     if winCallback and failCallback:
         t = Thread(target=self.loadCurrentTracksWorker, args=(winCallback, failCallback, progressCallback))
         t.daemon=True
         t.start()
     else:
         existingTracksFilenames = os.listdir(self.tracks_user_dir)
         self.tracks.clear()
         self.trackList.clear()
         trackCount = len(existingTracksFilenames)
         count = 0
         for trackPath in existingTracksFilenames:
             try:
                 json_data = open(self.tracks_user_dir + '/' + trackPath)
                 trackJson = json.load(json_data)
                 trackMap = TrackMap()
                 trackMap.fromJson(trackJson)
                 venueNode = trackJson['venue']
                 if venueNode:
                     venue = Venue()
                     venue.fromJson(venueNode)
                     self.tracks[venue.venueId] = trackMap
                 count += 1
                 if progressCallback:
                     progressCallback(count, trackCount, trackMap.name)
             except Exception as detail:
                 Logger.warning('TrackManager: failed to read track file ' + trackPath + ';\n' + str(detail))
         del self.trackIdsInRegion[:]
         self.trackIdsInRegion.extend(self.tracks.keys())
    def status(self, status, msg, status_code):
        Logger.debug("TelemetryManager: got telemetry status: " + str(status) + " message: " + str(msg) + " code: " + str(status_code))
        if status_code == TelemetryConnection.STATUS_CONNECTED:
            self.dispatch('on_connected', msg)
        elif status_code == TelemetryConnection.STATUS_AUTHORIZED:
            self._retry_count = 0
        elif status_code == TelemetryConnection.ERROR_AUTHENTICATING:
            Logger.warning("TelemetryManager: authentication failed")
            self._auth_failed = True
            self.stop()
            self.dispatch('on_auth_error', "Podium: invalid device id")
        elif status_code == TelemetryConnection.STATUS_DISCONNECTED:
            Logger.info("TelemetryManager: disconnected")
            self.stop()
            if not self._auth_failed:
                self.dispatch('on_disconnected', msg)

            if self._should_connect and not self._auth_failed:
                wait = self.RETRY_WAIT_START if self._retry_count == 0 else \
                    min(self.RETRY_WAIT_MAX_TIME, (math.pow(self.RETRY_MULTIPLIER, self._retry_count) *
                                                   self.RETRY_WAIT_START))
                Logger.warning("TelemetryManager: got disconnect, reconnecting in %d seconds" % wait)
                self._retry_timer = threading.Timer(wait, self._connect)
                self._retry_timer.start()
                self._retry_count += 1
        elif status_code == TelemetryConnection.STATUS_STREAMING:
            self.dispatch('on_streaming', True)
        elif status_code in [TelemetryConnection.ERROR_CONNECTING,
                             TelemetryConnection.ERROR_UNKNOWN,
                             TelemetryConnection.ERROR_UNKNOWN_MESSAGE]:
            self.dispatch('on_error', msg)
Пример #22
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)
Пример #23
0
 def downloadTrackList(self):
     start = 0
     totalVenues = None
     nextUri = self.rcp_venue_url + '?start=' + str(start)
     trackList = {}
     while nextUri:
         venuesDocJson = self.loadJson(nextUri)
         try:
             if totalVenues == None:
                 totalVenues = int(venuesDocJson.get('total', None))
                 if totalVenues == None:
                     raise Exception('Malformed venue list JSON: could not get total venue count')
             venuesListJson = venuesDocJson.get('venues', None)
             if venuesListJson == None:
                 raise Exception('Malformed venue list JSON: could not get venue list')
             for venueJson in venuesListJson:
                 venue = Venue()
                 venue.fromJson(venueJson)
                 trackList[venue.venueId] = venue
                             
             nextUri = venuesDocJson.get('nextURI')
         except Exception as detail:
             Logger.error('TrackManager: Malformed venue JSON from url ' + nextUri + '; json =  ' + str(venueJson) + ' ' + str(detail))
             
     retrievedVenueCount = len(trackList)
     Logger.info('TrackManager: fetched list of ' + str(retrievedVenueCount) + ' tracks')                 
     if (not totalVenues == retrievedVenueCount):
         Logger.warning('TrackManager: track list count does not reflect downloaded track list size ' + str(totalVenues) + '/' + str(retrievedVenueCount))
     return trackList
Пример #24
0
    def _update_files(self, *args):
        # Clear current files
        self.dispatch('on_entries_cleared')
        self._items = []

        # Add the components that are always needed
        if platform == 'win':
            is_root = splitdrive(self.path)[1] in (sep, altsep)
        elif platform in ('macosx', 'linux', 'android', 'ios'):
            is_root = normpath(expanduser(self.path)) == sep
        else:
            # Unknown file system; Just always add the .. entry but also log
            Logger.warning('Filechooser: Unsupported OS: %r' % platform)
            is_root = False
        if not is_root:
            back = '..' + sep
            pardir = Builder.template(self._ENTRY_TEMPLATE, **dict(name=back,
                size='', path=back, controller=self, isdir=True, parent=None,
                sep=sep, get_nice_size=lambda: ''))
            self._items.append(pardir)
            self.dispatch('on_entry_added', pardir)
        try:
            self._add_files(self.path)
        except OSError:
            Logger.exception('Unable to open directory <%s>' % self.path)
Пример #25
0
 def purchase(self, sku):
     # Really need to move these debug settings to a global 
     # settings file. Oh and they say that global settings files are bad.
     # Let's get to the bottom of it.
     if DEBUG:
         self.debug_sku = sku
         sku = 'android.test.purchased'
         if sku not in self.skus:
             self.skus.append(sku)
         Logger.warning('IAB is running in DEBUG mode and won\'t buy anything!')
     if self.purchase_requested is not None:
         self._toast('purchase already in progress')
         return False
     elif self.syncing:
         self.purchase_requested = sku
         Clock.schedule_once(self._fail, TIMEOUT)
         self._toast('will start purchase shortly')
         return True
     else:
         Logger.info('Purchasing ' + sku)
         if not self.setup_complete:
             self._toast('will start purchase shortly')
         else:
             self._toast('purchase started')
         self.purchase_requested = sku
         Clock.schedule_once(self._fail, TIMEOUT)
         self._process_purchase()
         return True
Пример #26
0
    def _init_camera(self, camera_id):
        Logger.info('Init camera %d' % camera_id)
        if self._camera and self.camera_id == camera_id:
            return
        self._release_camera()
        if IsAndroid:
            self._camera = Camera.open(camera_id)
            parameters = self._camera.getParameters()            

            #print parameters.flatten()
            if parameters is None:
                Logger.warning('Can''t read parameters')
                return

            supportedSizes = parameters.getSupportedVideoSizes()
            if supportedSizes is None:
                supportedSizes = parameters.getSupportedPreviewSizes()
            
            sizes = []
            if supportedSizes is not None:
                  iterator = supportedSizes.iterator()
                  while iterator.hasNext():
                      cameraSize = iterator.next()
                      sizes.append((cameraSize.width, cameraSize.height))

            pickedSize = self._pick_optimal_size(sizes)

            # Update texture according to picked size
            self.resolution = list(pickedSize)

            parameters.setPreviewSize(*pickedSize)
            self._camera.setParameters(parameters)
            self._camera.setPreviewTexture(self._previewTexture)
Пример #27
0
    def on_activity_result(request_code, result_code, intent):
        if request_code != RESULT_LOAD_IMAGE:
            Logger.warning('user_select_image: ignoring activity result that was not RESULT_LOAD_IMAGE')
            return

        try:
            if result_code == Activity.RESULT_CANCELED:
                Clock.schedule_once(lambda dt: callback(None), 0)
                return

            if result_code != Activity.RESULT_OK:
                # This may just go into the void...
                raise NotImplementedError('Unknown result_code "{}"'.format(result_code))

            selectedImage = intent.getData()  # Uri
            filePathColumn = [MediaStore_Images_Media_DATA] # String[]
            # Cursor
            cursor = currentActivity.getContentResolver().query(selectedImage,
                    filePathColumn, None, None, None)
            cursor.moveToFirst()

            # int
            columnIndex = cursor.getColumnIndex(filePathColumn[0])
            # String
            picturePath = cursor.getString(columnIndex)
            cursor.close()
            Logger.info('android_ui: user_select_image() selected %s', picturePath)

            # This is possibly in a different thread?
            Clock.schedule_once(lambda dt: callback(picturePath), 0)

        finally:
            activity.unbind(on_activity_result=on_activity_result)
Пример #28
0
    def append(category, key, obj, timeout=None):
        '''Add a new object in the cache.

        :Parameters:
            `category` : str
                Identifier of the category
            `key` : str
                Uniq identifier of the object to store
            `obj` : object
                Object to store in cache
            `timeout` : double (optionnal)
                Custom time to delete the object if it's not used.
        '''
        try:
            cat = Cache._categories[category]
        except KeyError:
            Logger.warning('Cache: category <%s> not exist' % category)
            return
        timeout = timeout or cat['timeout']
        # FIXME: activate purge when limit is hit
        #limit = cat['limit']
        #if limit is not None and len(Cache._objects[category]) >= limit:
        #    Cache._purge_oldest(category)
        Cache._objects[category][key] = {
            'object': obj,
            'timeout': timeout,
            'lastaccess': Clock.get_time(),
            'timestamp': Clock.get_time()}
Пример #29
0
    def _update_files(self, *args):
        # Clear current files
        self.dispatch("on_entries_cleared")

        # Add the components that are always needed
        if platform == "win32":
            is_root = splitdrive(self.path)[1] in (sep, altsep)
        elif platform in ("darwin", "linux2"):
            is_root = normpath(expanduser(self.path)) == sep
        else:
            # Unknown file system; Just always add the .. entry but also log
            Logger.warning("Filechooser: Unsupported OS: %r" % platform)
            is_root = False
        if not is_root:
            back = ".." + sep
            pardir = Builder.template(
                self._ENTRY_TEMPLATE,
                **dict(
                    name=back,
                    size="",
                    path=back,
                    controller=self,
                    isdir=True,
                    parent=None,
                    sep=sep,
                    get_nice_size=lambda: "",
                )
            )
            self.dispatch("on_entry_added", pardir)
        try:
            self._add_files(self.path)
        except OSError, e:
            Logger.exception("Unable to open directory <%s>" % self.path)
Пример #30
0
def _on_gstplayer_message(mtype, message):
    if mtype == 'error':
        Logger.error('AudioGstplayer: {}'.format(message))
    elif mtype == 'warning':
        Logger.warning('AudioGstplayer: {}'.format(message))
    elif mtype == 'info':
        Logger.info('AudioGstplayer: {}'.format(message))
Пример #31
0
    def lzw_decode(self, input, initial_codesize, color_table_size):
        '''Decodes a lzw stream from input import
        Returns list of ints (pixel values)'''
        string_table = {}
        output = array('B')
        output_append = output.append
        output_extend = output.extend
        old = ''
        index = 0

        bits = self.string_to_bits(input)
        self.bitpointer = 0

        codesize = initial_codesize + 1
        clearcode, end_of_info = color_table_size, color_table_size + 1

        if Debug:
            print('codesize: %d' % codesize)
            print('clearcode %d, end_of_info: %d' % (clearcode, end_of_info))

        def pop(size, _bits):
            ''' return bits '''
            start = self.bitpointer
            end = self.bitpointer = start + size
            return _bits[start:end]

        def clear():
            '''Called on clear code'''
            string_table.clear()
            for index in range(color_table_size):
                string_table[index] = chr(index)
            index = end_of_info + 1
            return index

        index = clear()
        # skip first (clear)code
        bits = bits[codesize:]
        # read first code, append to output
        self_bits_to_int = self.bits_to_int

        code = self_bits_to_int(pop(codesize, bits))
        if code in string_table:
            output_append(ord(string_table[code]))
        else:
            Logger.warning('Image_GIF: decoding error on code '
                           '<%d> aode size <%d>' % (code, codesize))
            string_table[code] = string_table[0]
            output_append(ord(string_table[code]))
        old = string_table[code]
        bitlen = len(bits)

        while self.bitpointer < bitlen:
            # read next code
            code = self_bits_to_int(pop(codesize, bits))

            # special code?
            if code == clearcode:
                index = clear()
                codesize = initial_codesize + 1
                code = self_bits_to_int(pop(codesize, bits))
                if code in string_table:
                    output_append(ord(string_table[code]))
                else:
                    Logger.warning('Image_GIF: decoding error on code '
                                   '<%d> aode size <%d>' % (code, codesize))
                    string_table[code] = string_table[0]
                    output_append(ord(string_table[code]))
                old = string_table[code]
                continue

            elif code == end_of_info:
                break

            # code in stringtable?
            if code in string_table:
                c = string_table[code]
                string_table[index] = ''.join((old, c[0]))
            else:
                c = ''.join((old, old[0]))
                string_table[code] = c

            index += 1
            old = c
            output_extend(list(map(ord, c)))

            if index == 2**codesize:
                codesize += 1
                if codesize == 13:
                    codesize = 12

        if self.debug_enabled:
            print('Output stream len: %d' % len(output))
        return output
Пример #32
0
            **kwargs)  # top-right diagonal
    kwargs.update(transform=ax2.transAxes)  # switch to the bottom axes
    ax2.plot((-diag, +diag), (1 - diag, 1 + diag),
             **kwargs)  # bottom-left diagonal
    ax2.plot((1 - diag, 1 + diag), (1 - diag, 1 + diag),
             **kwargs)  # bottom-right diagonal
    func.suptitle(str(chemin))
    plt.xlabel('Date')
    plt.ylabel('Conso (en mA)')
    plt.savefig(nom_graph)


if __name__ == "__main__":
    """
    Fonction main, pour lancer le script gengraph directement depuis le terminal
    """
    if (len(sys.argv) != 2) and (len(sys.argv) != 3) and (len(sys.argv) != 7):
        Logger.warning(
            'ERROR: Nombre d\'argument invalide : nombre d\'argument : {}'.
            format(len(sys.argv)))
    elif len(sys.argv) == 2:
        CHEMIN = sys.argv[1]
        generer_graph(CHEMIN)
    elif len(sys.argv) == 3:
        CHEMIN = sys.argv[1]
        CHEMIN_GRAPH = sys.argv[2]
        generer_graph(CHEMIN, CHEMIN_GRAPH)
    elif len(sys.argv) == 7:
        generer_graph(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4],
                      sys.argv[5], sys.argv[6])
Пример #33
0
    version = Config.getdefaultint('kivy', 'config_version', 0)

    # Add defaults section
    Config.adddefaultsection('kivy')
    Config.adddefaultsection('graphics')
    Config.adddefaultsection('input')
    Config.adddefaultsection('postproc')
    Config.adddefaultsection('widgets')
    Config.adddefaultsection('modules')
    Config.adddefaultsection('network')

    # Upgrade default configuration until we have the current version
    need_save = False
    if version != KIVY_CONFIG_VERSION and 'KIVY_NO_CONFIG' not in environ:
        Logger.warning('Config: Older configuration version detected'
                       ' ({0} instead of {1})'.format(version,
                                                      KIVY_CONFIG_VERSION))
        Logger.warning('Config: Upgrading configuration in progress.')
        need_save = True

    while version < KIVY_CONFIG_VERSION:
        Logger.debug('Config: Upgrading from %d to %d' %
                     (version, version + 1))

        if version == 0:

            # log level
            Config.setdefault('kivy', 'keyboard_repeat_delay', '300')
            Config.setdefault('kivy', 'keyboard_repeat_rate', '30')
            Config.setdefault('kivy', 'log_dir', 'logs')
            Config.setdefault('kivy', 'log_enable', '1')
Пример #34
0
def log_warning(text):
    if not ignore_warnings:
        Logger.warning(text)
Пример #35
0
 def restore(self):
     if self._is_desktop:
         self._win.restore_window()
     else:
         Logger.warning('Window: restore() is used only on desktop OSes.')
Пример #36
0
 def minimize(self):
     if self._is_desktop:
         self._win.minimize_window()
     else:
         Logger.warning('Window: minimize() is used only on desktop OSes.')
Пример #37
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)

            # 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()

            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')
Пример #38
0
def require(version):
    '''Require can be used to check the minimum version required to run a Kivy
    application. For example, you can start your application code like this::

        import kivy
        kivy.require('1.0.1')

    If a user attempts to run your application with a version of Kivy that is
    older than the specified version, an Exception is raised.

    The Kivy version string is built like this::

        X.Y.Z[-tag[-tagrevision]]

        X is the major version
        Y is the minor version
        Z is the bugfixes revision

    The tag is optional, but may be one of 'dev', 'alpha', or 'beta'.
    The tagrevision is the revision of the tag.

    .. warning::

        You must not ask for a version with a tag, except -dev. Asking for a
        'dev' version will just warn the user if the current Kivy
        version is not a -dev, but it will never raise an exception.
        You must not ask for a version with a tagrevision.

    '''
    def parse_version(version):
        # check for tag
        tag = None
        tagrev = None
        if '-' in version:
            l = version.split('-')
            if len(l) == 2:
                version, tag = l
            elif len(l) == 3:
                version, tag, tagrev = l
            else:
                raise Exception('Revision format must be X.Y.Z[-tag]')

        # check x y z
        l = version.split('.')
        if len(l) != 3:
            raise Exception('Revision format must be X.Y.Z[-tag]')
        return [int(x) for x in l], tag, tagrev

    # user version
    revision, tag, tagrev = parse_version(version)
    # current version
    sysrevision, systag, systagrev = parse_version(__version__)

    # ensure that the required version don't contain tag, except dev
    if tag not in (None, 'dev'):
        raise Exception('Revision format must not have any tag except "dev"')
    if tag == 'dev' and systag != 'dev':
        Logger.warning('Application requested a -dev version of Kivy. '
                       '(You have %s, but the application requires %s)' %
                       (__version__, version))
    # not tag rev (-alpha-1, -beta-x) allowed.
    if tagrev is not None:
        raise Exception('Revision format must not contain any tagrevision')

    # finally, checking revision
    if sysrevision < revision:
        raise Exception('The version of Kivy installed on this system '
                        'is too old. '
                        '(You have %s, but the application requires %s)' %
                        (__version__, version))
Пример #39
0
    'clipboard': ('android', 'winctypes', 'xsel', 'dbusklipper', 'nspaste',
                  'sdl2', 'pygame', 'dummy'),
}

# Read environment
for option in kivy_options:
    key = 'KIVY_%s' % option.upper()
    if key in environ:
        try:
            if type(kivy_options[option]) in (list, tuple):
                kivy_options[option] = environ[key].split(',')
            else:
                kivy_options[option] = environ[key].lower() in \
                    ('true', '1', 'yes', 'yup')
        except Exception:
            Logger.warning('Core: Wrong value for %s environment key' % key)
            Logger.exception('')

# Extract all needed path in kivy
#: Kivy directory
kivy_base_dir = dirname(sys.modules[__name__].__file__)
#: Kivy modules directory

kivy_modules_dir = environ.get('KIVY_MODULES_DIR',
                               join(kivy_base_dir, 'modules'))
#: Kivy extension directory
kivy_exts_dir = environ.get('KIVY_EXTS_DIR', join(kivy_base_dir, 'extensions'))
#: Kivy data directory
kivy_data_dir = environ.get('KIVY_DATA_DIR', join(kivy_base_dir, 'data'))
#: Kivy glsl shader directory
kivy_shader_dir = join(kivy_data_dir, 'glsl')
Пример #40
0
 def _pop_style(self, k):
     if k not in self._style_stack or len(self._style_stack[k]) == 0:
         Logger.warning('Label: pop style stack without push')
         return
     v = self._style_stack[k].pop()
     self.options[k] = v
Пример #41
0
def runTouchApp(widget=None, slave=False):
    '''Static main function that starts the application loop.
    You got some magic things, if you are using argument like this :

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

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

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

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

    '''

    from kivy.input import MotionEventFactory, kivy_postproc_modules

    # Ok, we got one widget, and we are not in slave mode
    # so, user don't create the window, let's create it for him !
    if widget:
        EventLoop.ensure_window()

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

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

        # create provider
        p = provider(key, args)
        if p:
            EventLoop.add_input_provider(p, True)

    # add postproc modules
    for mod in kivy_postproc_modules.values():
        EventLoop.add_postproc_module(mod)

    # add main widget
    if widget and EventLoop.window:
        if widget not in EventLoop.window.children:
            EventLoop.window.add_widget(widget)

    # start event loop
    Logger.info('Base: Start application main loop')
    EventLoop.start()

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

    # in non-slave mode, they are 2 issues
    #
    # 1. if user created a window, call the mainloop from window.
    #    This is due to glut, it need to be called with
    #    glutMainLoop(). Only FreeGLUT got a gluMainLoopEvent().
    #    So, we are executing the dispatching function inside
    #    a redisplay event.
    #
    # 2. if no window is created, we are dispatching event lopp
    #    ourself (previous behavior.)
    #
    try:
        if EventLoop.window is None:
            _run_mainloop()
        else:
            EventLoop.window.mainloop()
    finally:
        stopTouchApp()
Пример #42
0
    def load(self, filename):
        try:
            try:
                im = GifDecoder(open(filename, 'rb').read())
            except UnicodeEncodeError:
                if PY2:
                    im = GifDecoder(open(filename.encode('utf8'), 'rb').read())
        except:
            Logger.warning('Image: Unable to load Image <%s>' % filename)
            raise

        if Debug:
            print(im.print_info())
        img_data = []
        ls_width = im.ls_width
        ls_height = im.ls_height
        im_images = im.images
        im_palette = im.palette
        pixel_map = array('B', [0] * (ls_width * ls_height * 4))
        for img in im_images:
            palette = img.palette if img.local_color_table_flag\
                else im_palette
            have_transparent_color = img.has_transparent_color
            transparent_color = img.transparent_color
            #draw_method_restore_previous =  1 \
            #    if img.draw_method == 'restore previous' else 0
            draw_method_replace = 1 \
                if ((img.draw_method == 'replace') or
                    (img.draw_method == 'restore background')) else 0
            pixels = img.pixels
            img_height = img.height
            img_width = img.width
            left = img.left
            top = img.top
            if img_height > ls_height or img_width > ls_width or\
                top > ls_height or left > ls_width:
                Logger.warning('Image_GIF: decoding error on frame <%s>' %
                               len(img_data))
                img_height = ls_height
                img_width = ls_width
                left = top = 0
            #reverse top to bottom and left to right
            tmp_top = (ls_height - (img_height + top))
            img_width_plus_left = (img_width + left)
            ls_width_multiply_4 = ls_width * 4
            left_multiply_4 = left * 4
            img_data_append = img_data.append
            while img_height > 0:
                i = left
                img_height -= 1
                x = (img_height * img_width) - left
                rgba_pos = (tmp_top * ls_width_multiply_4) + (left_multiply_4)
                tmp_top += 1
                while i < img_width_plus_left:
                    #this should now display corrupted gif's
                    #instead of crashing on gif's not decoded properly
                    try:
                        (r, g, b) = palette[pixels[x + i]]
                    except:
                        rgba_pos += 4
                        i += 1
                        continue
                    # when not magic pink
                    if (r, g, b) != (255, 0, 255):
                        if have_transparent_color:
                            if transparent_color == pixels[x + i]:
                                if draw_method_replace:
                                    #transparent pixel draw method replace
                                    pixel_map[rgba_pos + 3] = 0
                                    rgba_pos += 4
                                    i += 1
                                    continue
                                #transparent pixel draw method combine
                                rgba_pos += 4
                                i += 1
                                continue
                        # this pixel isn't transparent
                        #doesn't have transparent color
                        (pixel_map[rgba_pos], pixel_map[rgba_pos + 1],
                         pixel_map[rgba_pos + 2]) = (r, g, b)
                        pixel_map[rgba_pos + 3] = 255
                    # if magic pink move to next pixel
                    rgba_pos += 4
                    i += 1

            img_data_append(
                ImageData(ls_width,
                          ls_height,
                          'rgba',
                          pixel_map.tostring(),
                          flip_vertical=False))
            if draw_method_replace:
                pixel_map = array('B', [0] * (ls_width * ls_height * 4))

        self.filename = filename

        return img_data
Пример #43
0
    version = Config.getdefaultint('kivy', 'config_version', 0)

    # Add defaults section
    Config.adddefaultsection('kivy')
    Config.adddefaultsection('graphics')
    Config.adddefaultsection('input')
    Config.adddefaultsection('postproc')
    Config.adddefaultsection('widgets')
    Config.adddefaultsection('modules')

    # Upgrade default configuration until we have the current version
    need_save = False
    if version != KIVY_CONFIG_VERSION and 'KIVY_NO_CONFIG' not in environ:
        Logger.warning('Config: Older configuration version detected'
                       ' ({0} instead of {1})'.format(version,
                                                      KIVY_CONFIG_VERSION))
        Logger.warning('Config: Upgrading configuration in progress.')
        need_save = True

    while version < KIVY_CONFIG_VERSION:
        Logger.debug('Config: Upgrading from %d to %d' %
                     (version, version + 1))

        if version == 0:

            # log level
            Config.setdefault('kivy', 'keyboard_repeat_delay', '300')
            Config.setdefault('kivy', 'keyboard_repeat_rate', '30')
            Config.setdefault('kivy', 'log_dir', 'logs')
            Config.setdefault('kivy', 'log_enable', '1')
def color_error(text):
    # show warning and return a sane value
    Logger.warning(text)
    return (0, 0, 0, 1)
Пример #45
0
    def Discover(self, **kwargs):

        oSendSocket = None
        oReceiveSocket = None
        iPort = 23272
        uSerial = kwargs.get('serialnumber', "")
        uConfigName = kwargs.get('configname', self.uConfigName)
        oSetting = self.GetSettingObjectForConfigName(uConfigName=uConfigName)
        fTimeOut = ToFloat(
            kwargs.get('timeout', oSetting.aScriptIniSettings.fTimeOut))
        del self.aResults[:]

        Logger.debug(u'Try to discover ELV MAX device:  %s ' % uSerial)

        try:
            oSendSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                                        socket.IPPROTO_UDP)
            oSendSocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST,
                                   True)
            oSendSocket.settimeout(10)

            bData = bytearray("eQ3Max", "utf-8") + \
                    bytearray("*\0",    "utf-8") + \
                    bytearray('*' * 10, "utf-8") + \
                    bytearray('I',      "utf-8")

            oSendSocket.sendto(bData, ("255.255.255.255", iPort))

            oReceiveSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            oReceiveSocket.settimeout(fTimeOut)
            oReceiveSocket.bind(("0.0.0.0", iPort))

            # sData, tSenderAddr = oReceiveSocket.recvfrom(50)
            # oRet = self.GetDeviceDetails(sData, tSenderAddr)
            # if uSerial == "" or oRet.uSerial == uSerial:
            #     self.aResults.append(oRet)

            while True:
                # we do not wait too long
                ready = select.select([oReceiveSocket], [], [], fTimeOut)
                if ready[0]:
                    # Get a response
                    sData, tSenderAddr = oReceiveSocket.recvfrom(50)
                    oRet = self.GetDeviceDetails(sData, tSenderAddr)
                    if uSerial == "" or oRet.uSerial == uSerial:
                        self.aResults.append(oRet)
                else:
                    break

            if oSendSocket:
                oSendSocket.close()
            if oReceiveSocket:
                oReceiveSocket.close()

            if len(self.aResults) > 0:
                return QueryDict([("Host", self.aResults[0].sFoundIP),
                                  ("Hostname",
                                   self.aResults[0].uFoundHostName),
                                  ("Serial", self.aResults[0].uFoundSerial),
                                  ("Name", self.aResults[0].uFoundName)])

        except Exception as e:
            pass

        if oSendSocket:
            oSendSocket.close()
        if oReceiveSocket:
            oReceiveSocket.close()

        Logger.warning(u'No ELV MAX Cube found %s' % uSerial)
        return QueryDict([("Host", ""), ("Hostname", ""), ("Serial", ""),
                          ("Name", "")])
Пример #46
0
from kivy.app import App
from kivy.logger import Logger
from os.path import dirname, join
from kivy.properties import NumericProperty, StringProperty, BooleanProperty, ListProperty, DictProperty, ObjectProperty
from kivy.clock import Clock
from kivy.core.window import Window
#Window.softinput_mode = "pan"

from msgbox import MsgBox
from saisie_mdp import SaisieMdp

try:
    from Crypto.Hash import SHA256
    IMPORT_SHA256 = True
except:
    Logger.warning('Application: Crypto.Hash.SHA256 non disponible')
    IMPORT_SHA256 = False

import GestionDB
import UTILS_Images
import UTILS_Config
import UTILS_Divers
import os
import sys
import shutil

runpath = os.path.dirname(os.path.realpath(sys.argv[0]))
os.chdir(runpath)

# Definition de l'icon app
from kivy.config import Config
Пример #47
0
from kivy.utils import platform as core_platform
from kivy.logger import Logger
from kivy.setupconfig import USE_SDL2

import kivy.input.providers.tuio
import kivy.input.providers.mouse

platform = core_platform

if platform == 'win' or 'KIVY_DOC' in os.environ:
    try:
        import kivy.input.providers.wm_touch
        import kivy.input.providers.wm_pen
    except:
        err = 'Input: WM_Touch/WM_Pen not supported by your version of Windows'
        Logger.warning(err)

if platform == 'macosx' or 'KIVY_DOC' in os.environ:
    try:
        import kivy.input.providers.mactouch
    except:
        err = 'Input: MacMultitouchSupport is not supported by your system'
        Logger.exception(err)

if platform == 'linux' or 'KIVY_DOC' in os.environ:
    try:
        import kivy.input.providers.probesysfs
    except:
        err = 'Input: ProbeSysfs is not supported by your version of linux'
        Logger.exception(err)
    try:
Пример #48
0
from plyer.utils import platform
from plyer.compat import PY2
from kivy.logger import Logger
if platform == 'android':
    from android.broadcast import BroadcastReceiver
    from . import notification
else:
    notification = None
    Logger.warning('Platform is not android, ignoring AndroidNotification and '
                   'BroadcastReceiver imports')


class Receiver(object):
    def __init__(self):
        self.registered = False
        self.intentName = ''
        self.actionName = ''

    def register(self, intentName, actionName, callback):
        self.br = BroadcastReceiver(self.on_broadcast,
                                    actions=[intentName + actionName])
        self.intentName = intentName
        self.actionName = actionName
        self.callback = callback
        self.registered = True

    def stop(self):
        if self.registered:
            self.br.stop()

    def start(self):
Пример #49
0
    def load_string(self, string, **kwargs):
        '''Insert a string into the Language Builder and return the root widget
        (if defined) of the kv string.

        :Parameters:
            `rulesonly`: bool, defaults to False
                If True, the Builder will raise an exception if you have a root
                widget inside the definition.
            `filename`: str, defaults to None
                If specified, the filename used to index the kv rules.

        The filename parameter can be used to unload kv strings in the same way
        as you unload kv files. This can be achieved using pseudo file names
        e.g.::

            Build.load_string("""
                <MyRule>:
                    Label:
                        text="Hello"
            """, filename="myrule.kv")

        can be unloaded via::

            Build.unload_file("myrule.kv")

        '''

        kwargs.setdefault('rulesonly', False)
        self._current_filename = fn = kwargs.get('filename', None)

        # put a warning if a file is loaded multiple times
        if fn in self.files:
            Logger.warning('Lang: The file {} is loaded multiples times, '
                           'you might have unwanted behaviors.'.format(fn))

        try:
            # parse the string
            parser = Parser(content=string, filename=fn)

            # merge rules with our rules
            self.rules.extend(parser.rules)
            self._clear_matchcache()

            # add the template found by the parser into ours
            for name, cls, template in parser.templates:
                self.templates[name] = (cls, template, fn)
                Factory.register(name,
                                 cls=partial(self.template, name),
                                 is_template=True,
                                 warn=True)

            # register all the dynamic classes
            for name, baseclasses in iteritems(parser.dynamic_classes):
                Factory.register(name,
                                 baseclasses=baseclasses,
                                 filename=fn,
                                 warn=True)

            # create root object is exist
            if kwargs['rulesonly'] and parser.root:
                filename = kwargs.get('rulesonly', '<string>')
                raise Exception('The file <%s> contain also non-rules '
                                'directives' % filename)

            # save the loaded files only if there is a root without
            # template/dynamic classes
            if fn and (parser.templates or parser.dynamic_classes
                       or parser.rules):
                self.files.append(fn)

            if parser.root:
                widget = Factory.get(parser.root.name)()
                self._apply_rule(widget, parser.root, parser.root)
                return widget
        finally:
            self._current_filename = None
Пример #50
0
def manipulação(fin, cod):

    '''
    Função para manipular o arquivo financeiro. 
    Limpeza, transforma dados, formata e cria novas colunas

    INPUT: DATAFRAME, DUPLICATAS CODE
    OUTPUT: CLEANED DATAFRAME
    '''
    
    Logger.info('MANIPULATE: MANIPULANDO O RELATORIO FINANCEIRO...\n')

    # EXCLUI COLUNAS NÃO UTLIZADAS E PREENCHE VALORES VAZIOS

    colunas = fin.columns

    for i in colunas:
        match = re.match('Data ', i)
        if match == True and i not in ["Data Entrada", "Data Emissão", "Data Vencimento", "Data Pagto Contábil"]:
            fin['Data Pagamento'] = fin[i]
            fin.drop(i, axis=1, inplace=True)
            break

    lista = ['Razão Social','Valor Líquido', 'Valor Parcela', 'Valor Abatimento', 'Valor Acréscimo', 'Data Pagamento', 'Observação','Nome Banco','Tipo Entrada', 'Banco']

    limpa(fin, lista)
    fin.fillna('', inplace = True)

    # TRANSFORMA OS VALORES DE STRING PARA FLOAT

    fun = lambda x: x.replace(".","").replace(",",".") if type(x) != float else x

    try:
        fin["Valor Líquido"] = fin["Valor Líquido"].apply(fun)
    except [ValueError, KeyError] as err:
        Logger.warning(f"MANIPULATE: {err} ao formatar a coluna 'Valor Liquido'! Talvez ela nao exista no arquivo")
        fin["Valor Parcela"] = fin["Valor Parcela"].apply(fun)
        pass
    
    try:
        fin["Valor Abatimento"] = fin["Valor Abatimento"].apply(fun)
        fin["Valor Acréscimo"] = fin["Valor Acréscimo"].apply(fun)
    except Exception as err:
        Logger.warning(f"MANIPULATE: {err} ao formatar a coluna 'Valor abatimento' e/ou 'Valor Acrescimo'! Talvez ela(s) nao exista(m) no arquivo")
        pass

    # RETIRA DA DATA O DIA DA SEMANA E SUBSTITUI A COLUNA NÃO FORMATADA

    fin["Data Pagamento"] = fin["Data Pagamento"].str.slice(stop = 10)
    fin.sort_values(by = ['Razão Social'], inplace = True)
    fin.reset_index(drop = True, inplace = True)

    # CRIA COLUNAS DE DÉBITO E CRÉDITO E PREENCHE COM A CONTA DE DUPLICATAS A COMPENSAR

    fin['DEBITO'] = ""
    fin['CREDITO'] = ""

    Logger.info('MANIPULATE: INSERINDO A CONTA CONTABIL DE DUPLICATAS PAGAS A COMPENSAR:')
    x = int(cod)

    try:
        for i in range(len(fin['Nome Banco'])):
            if fin['Nome Banco'][i] not in ['CAIXA LETICIA','DANIELA','CAIXA GERENCIAL','COFRE', 'LIVRO CAIXA - ARCAL']:
                fin['CREDITO'][i] = x
            else:
                fin['CREDITO'][i] = 5
    except KeyError as err:
        Logger.warning(f"MANIPULATE: {err} ao buscar a coluna 'Nome Banco'. Talvez ela nao exista no arquivo.")
        fin['CREDITO'] = x
Пример #51
0
                directory_created, file)
            print("        " + file_created)
            shutil.copyfile(os.path.join(directory, file), file_created)
        print()


__version__ = "2.4.1"
Logger.info("Creator Kivy Project version: " + __version__)

if len(sys.argv) <= 1:
    Logger.warning("""
Use a script with string arguments:

'name' - project name
'version' - project version
'path' - project directory
'repo' - address of the repository on GitHub (optional)
'author' - name of the author of the project (optional)
'mail' - mail of the author of the project (optional)
'site' - project site (optional)
""")
    sys.exit(0)

prog_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
sys.dont_write_bytecode = True

parser = argparse.ArgumentParser()
parser.add_argument("name", type=str, help="Project name")
parser.add_argument("version", type=str, help="Project version")
parser.add_argument("copyright", type=str, help="Copyright")
parser.add_argument("path", type=str, help="Project directory")
Пример #52
0
 def _keyboard_closed(self):
     Logger.warning('SL|Character: The keyboard is no longer accessible!')
     self._keyboard.unbind(on_key_down=self._on_keyboard_down)
     self._keyboard.unbind(on_key_up=self._on_keyboard_up)
     self._keyboard = None
Пример #53
0
            Logger.exception('Core: error while reading local' 'configuration')

    version = Config.getdefault('kivy', 'config_version', 0)

    # Add defaults section
    Config.adddefaultsection('kivy')
    Config.adddefaultsection('graphics')
    Config.adddefaultsection('input')
    Config.adddefaultsection('postproc')
    Config.adddefaultsection('widgets')
    Config.adddefaultsection('modules')

    # Upgrade default configuration until we have the current version
    need_save = False
    if version != KIVY_CONFIG_VERSION:
        Logger.warning('Config: Older configuration version detected'
                       ' (%d instead of %d)' % (version, KIVY_CONFIG_VERSION))
        Logger.warning('Config: Upgrading configuration in progress.')
        need_save = True

    while version < KIVY_CONFIG_VERSION:
        Logger.debug('Config: Upgrading from %d to %d' %
                     (version, version + 1))

        if version == 0:

            # log level
            Config.setdefault('kivy', 'keyboard_repeat_delay', '300')
            Config.setdefault('kivy', 'keyboard_repeat_rate', '30')
            Config.setdefault('kivy', 'log_dir', 'logs')
            Config.setdefault('kivy', 'log_enable', '1')
            Config.setdefault('kivy', 'log_level', 'info')
Пример #54
0
    def ExecuteActionModifyFile(self, oAction: cAction) -> eReturnCode:
        """
        WikiDoc:Doc
        WikiDoc:Context:ActionsDetails
        WikiDoc:Page:Actions-ModifyFile
        WikiDoc:TOCTitle:modifyfile
        = modifyfile =
        Provides some common file operations like copy, rename, delete. All Operations can only be performed on files within the definition folder, so all pathes must be relative to the definition root folder. For copyfolder the abspath argument gives you access as a source for folder outside the definition folder
        This action will modify the error code (0=success, 1=failure), existfile will not modify the error code

        <div style="overflow:auto; ">
        {| class="wikitable"
        ! align="left" | Attribute
        ! align="left" | Description
        |-
        |string
        |modifyfile
        |-
        |filename
        |Relative path to file name
        |-
        |path
        |Relative path
        |-
        |abspath
        |Absolute path to source folder (copyfolder only)
        |-
        |dstfilename
        |For copy,rename and zip... the destination file name
        |-
        |dstpath
        |For copy,rename... the destination path name
        |-
        |dstvarname
        |for exist the destination var for the result
        |-
        |removepath
        |for zip: the path to remove from the zip directory
        |-
        |skipfiles
        |for zipfolder: filenames to exclude from the zip file (list)
        |-
        |Operator
        |Operator for the command. Use one of the following keywords
        * "copyfile"
        * "copyfolder"
        * "renamefile"
        * "renamefolder"
        * "deletefile"
        * "createfolder"
        * "deletefolder"
        * "existfile"
        * "existfolder"
        * "zipfile"
        * "zipfolder"

        |}</div>

        exist returns "TRUE" or "FALSE"

        A short example:
        <div style="overflow-x: auto;"><syntaxhighlight  lang="xml">
        <action name="" string="modifyfile" filename="definition.ini" operator="copy" dstfilename="definition.old"/>
        </syntaxhighlight></div>
        WikiDoc:End
        """

        oDestFileName: cFileName
        oPath: cPath

        uFileName: str = oAction.dActionPars.get("filename", "")
        uDestFileName: str = oAction.dActionPars.get("dstfilename", "")
        uPath: str = oAction.dActionPars.get("path", "")
        uDestPath: str = oAction.dActionPars.get("dstpath", "")

        uDestVarName: str = oAction.dActionPars.get("dstvarname", "")
        uOperator: str = ReplaceVars(oAction.dActionPars.get("operator", ""))
        uAbsPath: str = ReplaceVars(oAction.dActionPars.get("abspath", ""))
        uRemovePath: str = ReplaceVars(
            oAction.dActionPars.get("removepath", ""))
        aSkipFiles: List[str] = ToList(
            ReplaceVars(oAction.dActionPars.get("skipfiles", '[]')))
        aSkipFiles.append("*.ini")
        aSkipFiles.append("*.pyc")

        self.oEventDispatcher.LogAction(uTxt=u'ModifyFile', oAction=oAction)

        if uFileName.startswith('$var(DEFINITIONPATH'):
            oFileName = cFileName().ImportFullPath(uFnFullName=uFileName)
        else:
            oFileName = cFileName(
                Globals.oDefinitionPathes.oPathDefinition) + uFileName

        if uPath.startswith('$var(DEFINITIONPATH'):
            oPath = cPath(uPath)
        else:
            oPath = cPath(Globals.oDefinitionPathes.oPathDefinition) + uPath

        oAbsPath: cPath = cPath(uAbsPath)

        if uDestFileName.startswith('$var(DEFINITIONPATH'):
            oDestFileName = cFileName().ImportFullPath(
                uFnFullName=uDestFileName)
        else:
            oDestFileName = cFileName(
                Globals.oDefinitionPathes.oPathDefinition) + uDestFileName

        if uDestPath.startswith('$var(DEFINITIONPATH'):
            oDestPath = cPath(uDestPath)
        else:
            oDestPath = cPath(
                Globals.oDefinitionPathes.oPathDefinition) + uDestPath

        if ".." in oFileName.string:
            Logger.warning(
                u'Action: ModifyFile: File must be inside definition folder:' +
                oFileName.string)
            return eReturnCode.Error

        if ".." in oDestFileName.string:
            Logger.warning(
                u'Action: ModifyFile: Destination File must be inside definition folder:'
                + oDestFileName.string)
            return eReturnCode.Error

        if ".." in oPath.string:
            Logger.warning(
                u'Action: ModifyFile: Path must be inside definition folder:' +
                oPath.string)
            return eReturnCode.Error

        if ".." in oDestPath.string:
            Logger.warning(
                u'Action: ModifyFile: Destination Path must be inside definition folder:'
                + oDestPath.string)
            return eReturnCode.Error

        if uOperator == u'copyfile':
            if oFileName.Copy(oNewFile=oDestFileName):
                return eReturnCode.Success
            else:
                return eReturnCode.Error
        elif uOperator == u'renamefile':
            if oFileName.Rename(oNewFileName=oDestFileName):
                return eReturnCode.Success
            else:
                return eReturnCode.Error
        elif uOperator == u'deletefile':
            if oFileName.Delete():
                return eReturnCode.Success
            else:
                return eReturnCode.Error
        elif uOperator == u'existfile':
            if oFileName.Exists():
                SetVar(uVarName=uDestVarName, oVarValue="TRUE")
            else:
                SetVar(uVarName=uDestVarName, oVarValue="FALSE")
            return eReturnCode.Nothing
        elif uOperator == u'copyfolder':
            if oAbsPath.IsEmpty():
                if oPath.Copy(oDest=oDestPath):
                    return eReturnCode.Success
                else:
                    return eReturnCode.Error
            else:
                if oAbsPath.Copy(oDest=oDestPath):
                    return eReturnCode.Success
                else:
                    return eReturnCode.Error
        elif uOperator == u'renamefolder':
            if oPath.Rename(oNewPath=oDestPath):
                return eReturnCode.Success
            else:
                return eReturnCode.Error
        elif uOperator == u'deletefolder':
            if oPath.Delete():
                return eReturnCode.Success
            else:
                return eReturnCode.Error
        elif uOperator == u'createfolder':
            if oPath.Create():
                return eReturnCode.Success
            else:
                return eReturnCode.Error
        elif uOperator == u'existfolder':
            if oPath.Exists():
                SetVar(uVarName=uDestVarName, oVarValue="TRUE")
            else:
                SetVar(uVarName=uDestVarName, oVarValue="FALSE")
            return eReturnCode.Success
        elif uOperator == u'zipfolder':
            oZipFolder: cZipPath = cZipPath(
                ReplaceVars(oAction.dActionPars.get("path", "")))
            oDestFileName = cFileName('').ImportFullPath(
                uFnFullName=ReplaceVars(
                    oAction.dActionPars.get("dstfilename", "")))
            if oZipFolder.ZipFolder(oFnZipDest=oDestFileName,
                                    uRemovePath=uRemovePath,
                                    aSkipFiles=aSkipFiles):
                return eReturnCode.Success
            else:
                return eReturnCode.Error
        elif uOperator == u'zipfile':
            oZipFile: cZipFile = cast(
                cZipFile,
                cZipFile().ImportFullPath(uFnFullName=ReplaceVars(
                    oAction.dActionPars.get("filename", ""))))
            oDestFileName = cFileName('').ImportFullPath(
                uFnFullName=ReplaceVars(
                    oAction.dActionPars.get("dstfilename", "")))
            if oZipFile.ZipFile(oZipDest=oDestFileName,
                                uRemovePath=uRemovePath):
                return eReturnCode.Success
            else:
                return eReturnCode.Error
        else:
            LogError(uMsg=u'Action: ModifyFile: Wrong modifier:' + uOperator)
            return eReturnCode.Error
Пример #55
0
def warn(title, text):
    Logger.warning(title + ' : ' + text)
Пример #56
0
    def load_map(self, map):
        """Load a map."""
        #Unload the current map first
        self.unload_map()

        #Locate the XML file for the map
        Logger.info("Loading map '{}'...".format(map))
        map_file = os.path.join(map, os.path.basename(map) + ".xml")

        if not os.path.exists(map_file):
            Logger.error("Failed to load map file '{}'.".format(map_file))
            return False

        #Load the map XML file
        xml = etree.parse(map_file)
        root = xml.getroot()

        for child in root:
            #Terrain?
            if child.tag == "terrain":
                #Validate terrain
                if not ("size" in child.attrib and "spawnpos" in child.attrib
                        and "heightmap" in child.attrib):
                    Logger.error(
                        "Terrain section must define 'size', 'spawnpos', and 'heightmap'."
                    )
                    return False

                #Load terrain
                self.size = parse_vec(child.attrib["size"], 3)
                self.spawnpos = parse_vec(child.attrib["spawnpos"], 2)
                heightmap = os.path.join(map, child.attrib["heightmap"])

                self.terrain = GeoMipTerrain("Terrain")
                self.terrain.set_block_size(64)
                self.terrain.set_bruteforce(True)

                if not self.terrain.set_heightfield(heightmap):
                    Logger.error("Failed to load heightmap for terrain.")
                    self.terrain = None
                    return False

                self.terrain_np = self.terrain.get_root()
                self.terrain_np.set_scale(self.size[0] / 512,
                                          self.size[1] / 512, self.size[2])
                tex = loader.load_texture(
                    "./data/textures/terrain/grass_tex2.png")
                self.terrain_np.set_texture(tex)
                self.terrain_np.set_tex_scale(TextureStage.get_default(),
                                              self.size[0] / 512,
                                              self.size[1] / 512)
                tex.set_wrap_u(Texture.WM_repeat)
                tex.set_wrap_v(Texture.WM_repeat)
                self.terrain_np.reparent_to(render)
                self.terrain.generate()

                base.camera.set_pos(self.size[0] / 2, self.size[1] / 2,
                                    self.size[2])

            #Portal?
            elif child.tag == "portal":
                #Validate portal
                if not ("pos" in child.attrib and "destmap" in child.attrib):
                    Logger.warning("Portal must define 'pos' and 'destmap'.")
                    continue

                #Load portal
                pos = parse_vec(child.attrib["pos"], 3)
                radius = parse_float(
                    child.attrib["radius"]) if "radius" in child.attrib else 1
                destmap = child.attrib["destmap"]
                self.add_portal(pos, radius, destmap)

            #Gate?
            elif child.tag == "gate":
                #Validate gate
                if not ("pos" in child.attrib and "destmap" in child.attrib
                        and "destvec" in child.attrib):
                    Logger.warning(
                        "Gate must define 'pos', 'destmap', and 'destvec'.")
                    continue

                #Load gate
                pos = parse_vec(child.attrib["pos"], 3)
                destmap = child.attrib["destmap"]
                destvec = parse_vec(child.attrib["destvec"], 3)
                material = child.attrib[
                    "material"] if "material" in child.attrib else ""
                self.add_gate(pos, destmap, destvec, material)

            #Object?
            elif child.tag == "object":
                #Validate object
                if not ("mesh" in child.attrib and "pos" in child.attrib):
                    Logger.warning("Object must define 'mesh' and 'pos'.")
                    continue

                #Load object
                mesh = child.attrib["mesh"]
                pos = parse_vec(child.attrib["pos"], 3)
                rot = parse_vec(child.attrib["rot"],
                                3) if "rot" in child.attrib else [0, 0, 0]
                scale = parse_vec(child.attrib["scale"],
                                  3) if "scale" in child.attrib else [1, 1, 1]
                material = child.attrib[
                    "material"] if "material" in child.attrib else ""
                sound = child.attrib["sound"] if "sound" in child.attrib else ""
                self.add_object(mesh, pos, rot, scale, material, sound)

            #Object Group?
            elif child.tag == "objectgroup":
                #Validate object group
                if not ("mesh" in child.attrib):
                    Logger.warning("Object group must define 'mesh'.")
                    continue

                #Load object group
                mesh = child.attrib["mesh"]
                material = child.attrib[
                    "material"] if "material" in child.attrib else ""
                self.load_object_group(child, mesh, material)

            #Unknown?
            else:
                Logger.warning(
                    "Unknown tag '{}' encountered in map '{}'.".format(
                        child.tag, map))

        #Map loaded
        Logger.info("Map '{}' loaded.".format(map))
        return True
Пример #57
0
 def raise_window(self):
     if self._is_desktop:
         self._win.raise_window()
     else:
         Logger.warning('Window: show() is used only on desktop OSes.')
Пример #58
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_option('network', 'useragent'):
                    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
Пример #59
0
 def hide(self):
     if self._is_desktop:
         self._win.hide_window()
     else:
         Logger.warning('Window: hide() is used only on desktop OSes.')
Пример #60
0
    def ExecuteActionDefineTimer(self, oAction: cAction) -> eReturnCode:
        """
        WikiDoc:Doc
        WikiDoc:Context:ActionsDetails
        WikiDoc:Page:Actions-DefineTimer
        WikiDoc:TOCTitle:definetimer
        = definetimer =
        Sets or removes a timer for actions. With a timer, you can perform actions in intervals. A predefined timer is a timer to update clock widgets.
        This action will modify the error code (0=success, 1=failure)

        <div style="overflow:auto; ">
        {| border=1 class="wikitable"
        ! align="left" | string
        ! align="left" | timername
        ! align="left" | interval
        ! align="left" | switch
        ! align="left" | actionname
        ! align="left" | doonpause
        |-
        |definetimer
        |Timer Name (Mandantory)
        |Time Interval in seconds
        |on / off : on to enable/set a timer, off to remove the timer
        |Action to execute by the timer
        |Execute the timer, even if the device is on sleep
        |}</div>

        If you want to change a timer, ou need to remove the timer and add it with the new settings
        WikiDoc:End
        """

        self.oEventDispatcher.LogAction(uTxt=u'DefineTimer', oAction=oAction)

        uTimerName: str = ReplaceVars(oAction.dActionPars.get("timername", ""))
        uInterval: str = ReplaceVars(oAction.dActionPars.get("interval", ""))
        uSwitch: str = ReplaceVars(oAction.dActionPars.get("switch", ""))
        uActionName: str = ReplaceVars(
            oAction.dActionPars.get("actionname", ""))
        bDoOnPause: bool = ToBool(
            ReplaceVars(oAction.dActionPars.get("doonpause", "0")))

        if uSwitch == u'on':
            if not self.oEventDispatcher.oAllTimer.HasTimer(
                    uTimerName=uTimerName):
                oCustomTimer: cCustomTimer = cCustomTimer(
                    uTimerName=uTimerName,
                    uActionName=uActionName,
                    fTimerIntervall=ToFloat(uInterval),
                    bDoOnPause=bDoOnPause)
                self.oEventDispatcher.oAllTimer.AddTimer(uTimerName=uTimerName,
                                                         oTimer=oCustomTimer)
                oCustomTimer.StartTimer()
                return eReturnCode.Success
            else:
                Logger.warning(u'Action: DefineTimer, timer already exist:' +
                               uTimerName)
                return eReturnCode.Error

        if uSwitch == u'off':
            if self.oEventDispatcher.oAllTimer.HasTimer(uTimerName=uTimerName):
                self.oEventDispatcher.oAllTimer.DeleteTimer(
                    uTimerName=uTimerName)
                return eReturnCode.Success
            else:
                Logger.warning(u'Action: DefineTimer, timer does not exist:' +
                               uTimerName)
                return eReturnCode.Error

        uMsg: str = u'Action: DefineTimer, you need to on/off the timer:' + uTimerName
        Logger.warning(uMsg)
        ShowErrorPopUp(uTitle='Warning', uMessage=uMsg)
        return eReturnCode.Error