Пример #1
0
    def refresh_session_list(self):
        try:
            self.clear_sessions()
            sessions = self.datastore.get_sessions()
            f = Filter().gt('LapCount', 0)
            session = None
            for session in sessions:
                session = self.append_session(session_id=session.session_id, name=session.name, notes=session.notes)
                dataset = self.datastore.query(sessions=[session.session_id],
                                        channels=['LapCount', 'LapTime'],
                                        data_filter=f,
                                        distinct_records=True)
        
                records = dataset.fetch_records()
                lap_count = 0
                for r in records:
                    lap_id = int(r[1])
                    laptime = r[2]
                    self.append_lap(session, lap_id, laptime)
                    lap_count += 1
                if lap_count == 0:
                    session.append_label('No Laps')

            self.sessions = sessions
            self.ids.session_alert.text = '' if session else 'No Sessions'
                
        except Exception as e:
            Logger.error('AnalysisView: unable to fetch laps: {}\n\{}'.format(e, traceback.format_exc()))            
Пример #2
0
    def __init__(self, serverip, serverport, team, nick, screenMgr):
        super(SpylightGame, self).__init__()
        self.screenMgr = screenMgr

        # Register to the server
        self._ni = NetworkInterface(serverip, serverport)
        init_response = self._ni.connect(MessageFactory.init(team, nick))

        # Parse server init message
        self.team = init_response['team']
        self.playerid = init_response['id']

        # Init environment
        loaded_map = SpyLightMap(init_response['map'])
        Logger.info("SL|SLGame: Map loaded: %s", loaded_map.title)
        Logger.info("SL|SLGame: Map size: %s", loaded_map.size)

        if init_response['map_hash'] != loaded_map.get_hash():
            Logger.error("SL|SLGame: Wrong map hash. Expected %s",
                         loaded_map.get_hash())
            sys.exit()

        self.init_game_view(loaded_map, init_response)

        self.hud = SpylightHUD(self, max_hp=init_response['max_hp'])
        self.add_widget(self.hud)

        # Register input listeners
        kbMgr = KeyboardManager()
        kbMgr.bind(quit=screenMgr.goToPauseScreen)
        self._am = ActionManager(self._ni, kbMgr, self)

        # Game client ready
        self._ni.on_message_recieved = self.update
        self._ni.ready()
Пример #3
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))
Пример #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 init_view(self):
        if self.settings and self.datastore:
            selection_settings_json = self.settings.userPrefs.get_pref('analysis_preferences', 'selected_sessions_laps')
            selection_settings = json.loads(selection_settings_json)
            delete_sessions = []

            session_selections = []
            # Load sessions first, then select the session
            for session_id_str, session_info in selection_settings["sessions"].iteritems():
                session = self.datastore.get_session_by_id(int(session_id_str))
                if session:
                    session_selections.append(session)
                else:
                    # If the session doesn't exist anymore, remove it from settings
                    delete_sessions.append(session_id_str)

            if len(delete_sessions) > 0:
                for session_id in delete_sessions:
                    selection_settings["sessions"].pop(session_id)

                # Resave loaded sessions and laps
                self._save()

            lap_selections = []
            for session_id_str, session_info in selection_settings["sessions"].iteritems():
                session_id = int(session_id_str)
                laps = session_info["selected_laps"]
                for lap in laps:
                    lap_selections.append((session_id, lap))
            Clock.schedule_once(lambda dt: self._load_next_selected_session(0, session_selections, lap_selections), 0.1)
        else:
            Logger.error("SessionListView: init_view failed, missing settings or datastore object")
            raise Exception("SessionListView: init_view failed, missing settings or datastore object")
Пример #6
0
def _on_gst_message(bus, message):
    Logger.trace('gst-bus: %s' % str(message))
    # log all error messages
    if message.type == gst.MESSAGE_ERROR:
        error, debug = list(map(str, message.parse_error()))
        Logger.error('gstreamer_video: %s' % error)
        Logger.debug('gstreamer_video: %s' % debug)
    def __init__(self, settings, channel, **kwargs):
        super(ChannelSelectView, self).__init__(**kwargs)
        self.register_event_type('on_channel_selected')
        self.register_event_type('on_channel_cancel')
        data = []
        channel_list = self.ids.channelList

        available_channels = list(settings.runtimeChannels.get_active_channels().iterkeys())
        available_channels.sort()
        try:
            for available_channel in available_channels:
                data.append({'text': available_channel, 'is_selected': False})
                
            args_converter = lambda row_index, rec: {'text': rec['text'], 'size_hint_y': None, 'height': dp(50)}
    
            list_adapter = ListAdapter(data=data,
                               args_converter=args_converter,
                               cls=ChannelItemButton,
                               selection_mode='single',
                               allow_empty_selection=True)
    
            channel_list.adapter = list_adapter

            #select the current channel
            index = 0
            for item in list_adapter.data:
                if item['text'] == channel:
                    view = list_adapter.get_view(index)
                    view.trigger_action(duration=0) #duration=0 means make it an instant selection
                index += 1

            list_adapter.bind(on_selection_change=self.on_select)
            self.channel = channel
        except Exception as e:
            Logger.error("ChannelSelectView: Error initializing: " + str(e))
Пример #8
0
    def _connection_thread_message_reader(self, rx_queue, connection, should_run):
        """This method is designed to be run in a thread, it will loop infinitely as long as should_run.is_set()
        returns True. In its loop it will attempt to read data from the socket connection

        :param rx_queue Queue for pushing data read from the socket onto
        :param connection Socket connection to read data from
        :param should_run Event to check on each loop to determine if to continue reading
        :type rx_queue threading.Queue
        :type connection SocketConnection
        :type should_run threading.Event
        :return: None
        """
        Logger.debug('SocketComm: connection thread message reader started')

        while should_run.is_set():
            try:
                msg = connection.read(should_run)
                if msg:
                    rx_queue.put(msg)
            except:
                Logger.error('SocketComm: Exception in connection_process_message_reader')
                Logger.debug(traceback.format_exc())
                should_run.clear()
                sleep(0.5)
        Logger.debug('SocketComm: connection process message reader exited')
Пример #9
0
 def on_channel_customization_close(self, instance, warn_range, alert_range, *args):
     try:
         self.warning = warn_range
         self.alert = alert_range
     except Exception as e:
         Logger.error("Gauge: Error customizing channel: " + str(e))
     self._dismiss_popup()
Пример #10
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)
Пример #11
0
    def idle(self):
        '''This function is called every frames. By default :
        * it "tick" the clock to the next frame
        * read all input and dispatch event
        * dispatch on_update + on_draw + on_flip on window
        '''

        # update dt
        Clock.tick()

        # read and dispatch input from providers
        self.dispatch_input()

        window = self.window
        if window and window.canvas.needs_redraw:
            Clock.tick_draw()
            window.dispatch('on_draw')
            window.dispatch('on_flip')

        # don't loop if we don't have listeners !
        if len(self.event_listeners) == 0:
            Logger.error('Base: No event listeners have been created')
            Logger.error('Base: Application will leave')
            self.exit()
            return False

        return self.quit
Пример #12
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))
Пример #13
0
    def __init__(self, device, args):
        super(MouseMotionEventProvider, self).__init__(device, args)
        self.waiting_event = deque()
        self.touches = {}
        self.counter = 0
        self.current_drag = None
        self.alt_touch = None
        self.disable_on_activity = False
        self.disable_multitouch = False
        self.multitouch_on_demand = False

        # split arguments
        args = args.split(',')
        for arg in args:
            arg = arg.strip()
            if arg == '':
                continue
            elif arg == 'disable_on_activity':
                self.disable_on_activity = True
            elif arg == 'disable_multitouch':
                self.disable_multitouch = True
            elif arg == 'multitouch_on_demand':
                self.multitouch_on_demand = True
            else:
                Logger.error('Mouse: unknown parameter <%s>' % arg)
Пример #14
0
 def __init__(self, **kwargs):
     super(ChannelSelectView, self).__init__(**kwargs)
     self.register_event_type('on_channel_selected')
     self.register_event_type('on_channel_cancel')
     
     settings = kwargs.get('settings')
     type = kwargs.get('type')
     channel = kwargs.get('channel')
     
     data = []
     channel_list = self.ids.channelList
     try:
         for available_channel,channelMeta in settings.runtimeChannels.channels.iteritems():
             channel_type = channelMeta.type
             data.append({'text': available_channel, 'is_selected': False})
             
         args_converter = lambda row_index, rec: {'text': rec['text'], 'size_hint_y': None, 'height': dp(50)}
 
         list_adapter = ListAdapter(data=data,
                            args_converter=args_converter,
                            cls=ChannelItemButton,
                            selection_mode='single',
                            allow_empty_selection=True)
 
         channel_list.adapter=list_adapter
         list_adapter.bind(on_selection_change=self.on_select)
         self.channel = channel
     except Exception as e:
         Logger.error("ChannelSelectView: Error initializing: " + str(e))
 def __init__(self,con):
     '''
     pass the connection object.
     '''
     self.con = con
     self.loaded = False
     loading = True
     lap = 0
     while loading:
         f = con.openFile(self.path)
         val = f.uread()
         f.close()
         self.lb_string = val
         try:
             self.lb = logback.Logback(val)
         except ValueError as e:
             if lap == 0:
                 Logger.info(("Octo.model: Value error while loading logback. "+
                       "This is probably due to it being corrupt."+
                       " Attepting to restore..."))
                 self.con.simple_sudo("cp {0}.bak {0}".format(self.path))
                 lap += 1
                 continue
             Logger.error("Octo.model: Can't fix logback. aborting")
             break
             
         loading = False
         self.loaded = True
Пример #16
0
 def sample_worker(self):
     rc_api = self._rc_api
     sample_event = self._sample_event
     
     Logger.info('DataBusPump: DataBus Sampler Starting')
     sample_event.clear()
     if sample_event.wait(SAMPLE_POLL_TEST_TIMEOUT) == True:
         Logger.info('DataBusPump: Async sampling detected')
     else:
         Logger.info('DataBusPump: Synchronous sampling mode enabled')
         while self._running.is_set():
             try:
                 #the timeout here is designed to be longer than the streaming rate of 
                 #RaceCapture. If we don't get an asynchronous sample, then we will timeout
                 #and request a sample anyway.
                 rc_api.sample()
                 sample_event.wait(SAMPLE_POLL_EVENT_TIMEOUT)
                 sample_event.clear()
                 sleep(SAMPLE_POLL_INTERVAL_TIMEOUT)
             except Exception as e:
                 sleep(SAMPLE_POLL_EXCEPTION_RECOVERY)
                 Logger.error('DataBusPump: Exception in sample_worker: ' + str(e))
             finally:
                 sample_event.clear()
             
     Logger.info('DataBusPump: DataBus Sampler Exiting')
     safe_thread_exit()
Пример #17
0
	def stop_preview(self):
		if self.camera:
			try:
				self.camera.stopPreview()
				pass
			except Exception as e:
				Logger.error('CameraPreview: stopPreview() exception %s' % e)
Пример #18
0
    def load_config(self):
        """(internal) This function is used for returning a ConfigParser with
        the application configuration. It's doing 3 things:

            #. Create an instance of a ConfigParser
            #. Load the default configuration by calling
               :meth:`build_config`, then
            #. If exist, load the application configuration file, or create it
               if it's not existing.

        :return: ConfigParser instance
        """
        self.config = config = ConfigParser()
        self.build_config(config)
        # if no sections are created, that's mean the user don't have
        # configuration.
        if len(config.sections()) == 0:
            return
        # ok, the user have some sections, read the default file if exist
        # or write it !
        filename = self.get_application_config()
        if filename is None:
            return config
        if exists(filename):
            try:
                config.read(filename)
            except:
                Logger.error("App: Corrupted config file, ignored.")
                self.config = config = ConfigParser()
                self.build_config(config)
                pass
        else:
            config.filename = filename
            config.write()
        return config
Пример #19
0
	def do_focus(self, fpoint):
		''' Call this to set the camera focus. `fpoint` is the center of the focus rect requested '''
		if all([self.play, self.focus_supported]):
			size = self.size
			msize = self.focus_rect_size
			if all([self.camera, self.params, min(fpoint) > 0, min(size) > 0, max(msize) > 0]):
				def to_focus_space(v):
					# focus coordinate space is [-1000, 1000]
					return (boundary(v, 0., 1.) * 2000) - 1000
				def get_ArrayList(area):
					array = ArrayList()
					array.add(CameraArea(Rect(*area), self.default_focus_weight))
					return array
				# get translated rect and convert to focus range
				focus_area = map(to_focus_space, self._rect_to_relative(fpoint, msize, size))
				try:
					self.camera.cancelAutoFocus()
					self.params.setFocusMode(Parameters.FOCUS_MODE_AUTO)
					if self.metering_areas_supported:
						metering_area = map(to_focus_space, self._rect_to_relative(
							fpoint,
							map(operator.mul, msize, [self.metering_area_factor] * 2),
							size)
						)
						self.params.setMeteringAreas(get_ArrayList(metering_area))
					self.params.setFocusAreas(get_ArrayList(focus_area))
					self.camera.setParameters(self.params)
					self.camera.setAutoFocusMoveCallback(_CameraFocusMoveCallback(self.on_focus_moving))
					self.camera.autoFocus(_CameraFocusCallback(self.focus_completed))
					return
				except Exception as e:
					Logger.error('CameraPreview: on_focus() exception %s' % e)

		self.dispatch('on_focus_completed', False)
		return False
Пример #20
0
	def update_parameters(self):
		if not self.camera:
			return
		self.params = params = self.camera.getParameters()
		if params is None:
			Logger.error('CameraPreview: can''t read parameters')
			return
		#
		# Preview settings
		#
		params.setAutoExposureLock(False)
		params.setVideoStabilization(True)
		params.setPreviewFpsRange(30000, 30000)
		#
		# Capture settings
		#
		params.setJpegQuality(90)
		params.setRotation(self.rotation)
		self.camera.setParameters(params)
		# get preview and picture size support
		self.supported_picture_sizes = map_List(
			lambda x: [x.width, x.height],
			params.getSupportedPictureSizes())
		self.supported_preview_sizes = map_List(
			lambda x: [x.width, x.height],
			params.getSupportedPreviewSizes())
		# get focus support
		self.focus_areas_supported = params.getMaxNumFocusAreas() > 0
		self.metering_areas_supported = params.getMaxNumMeteringAreas() > 0
		self.supported_focus_modes = map_List(
			lambda x: x,
			params.getSupportedFocusModes())
		self.autofocus_supported = Parameters.FOCUS_MODE_AUTO in self.supported_focus_modes
Пример #21
0
 def _on_gst_message(self, bus, message):
     t = message.type
     s = message.src.get_name()
     if t == gst.MESSAGE_EOS:
         self.stop()
     elif t == gst.MESSAGE_ERROR:
         self._pipeline.set_state(gst.STATE_NULL)
         err, debug = message.parse_error()
         Logger.error('AudioGstreamer: %s: %s' % (s,err))
         Logger.debug(str(debug))
         Logger.debug('Filename: %s' % self.filename)
         self._pipeline.set_state(gst.STATE_NULL)
     elif t == gst.MESSAGE_BUFFERING:
         buffer = message.parse_buffering()
         #Logger.debug('Audio buffering: %s' % buffer)
         if(self._loading):
             if(buffer > 10):
                 if self._loading:
                     self.dispatch('on_loaded')
                     self._loading = False
     elif t == gst.MESSAGE_STATE_CHANGED:
         old, new, pending = message.parse_state_changed()
         if (s == 'alsasink0'):
             Logger.debug('Audio state change: %s: %s -> %s (%s)' % (s, old, new, pending))
     elif t == gst.MESSAGE_ELEMENT:
         self.level_left = 36 - (message.structure['peak'][0] * -1)
         self.level_right = 36 - (message.structure['peak'][1] * -1)
         self.dispatch('on_level')
Пример #22
0
 def bar_value_percent(self, value):
     if (value >= 0) and (value <= 100):
         self.line_bar.bar_value = self._convert_to_value(value)
         self.line_bar.bar_value_percent = value
         self.line_bar.redraw_widget()
     else:
         Logger.error('ERROR: value < 0 OR value > 100. Try again.')
Пример #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 _on_gst_message(bus, message):
    Logger.trace("VideoGi: (bus) {}".format(message))
    # log all error messages
    if message.type == Gst.MessageType.ERROR:
        error, debug = list(map(str, message.parse_error()))
        Logger.error("VideoGi: {}".format(error))
        Logger.debug("VideoGi: {}".format(debug))
Пример #25
0
def CopyDir(uSrc,uDest, fIgnoreFiles=None):
    ''' copies a folder '''
    try:

        if IsDir(uSrc):
            aFiles = listdir(uSrc)
            if fIgnoreFiles is not None:
                aIgnored = fIgnoreFiles(uSrc, aFiles)
            else:
                aIgnored = set()

            if uSrc in aIgnored:
                return
            if not IsDir(uDest):
                CreateDir(uDest)

            for uFile in aFiles:
                if uFile not in aIgnored:

                    CopyDir(join(uSrc, uFile), join(uDest, uFile), fIgnoreFiles)
        else:
            CopyFile(uSrc, uDest)
    except Exception as e:
        uMsg=u'can\'t copy folder [%s] to [%s]: %s  ' % (uSrc,uDest,ToUnicode(e))
        Logger.error (uMsg)
        return False
Пример #26
0
Файл: image.py Проект: kivy/kivy
    def texture_update(self, *largs):
        if not self.source:
            self.texture = None
        else:
            filename = resource_find(self.source)
            self._loops = 0
            if filename is None:
                return Logger.error('Image: Error reading file {filename}'.
                                    format(filename=self.source))
            mipmap = self.mipmap
            if self._coreimage is not None:
                self._coreimage.unbind(on_texture=self._on_tex_change)
            try:
                if PY2 and isinstance(filename, str):
                    filename = filename.decode('utf-8')
                self._coreimage = ci = CoreImage(filename, mipmap=mipmap,
                                                 anim_delay=self.anim_delay,
                                                 keep_data=self.keep_data,
                                                 nocache=self.nocache)
            except:
                Logger.error('Image: Error loading texture {filename}'.
                                    format(filename=self.source))
                self._coreimage = ci = None

            if ci:
                ci.bind(on_texture=self._on_tex_change)
                self.texture = ci.texture
Пример #27
0
 def logout(self):
     super(AndroidGoogleClient, self).logout()
     if self.client and self.is_connected():
         try:
             self.client.disconnect()
         except JavaException:
             Logger.error("Google: error while logout")
Пример #28
0
 def on_tele_status(self, status):
     if not self.teleStatus:
         self.teleStatus = self.ids.teleStatus
     try:        
         self.teleStatus.color = self.telemetry_color[status]
     except:
         Logger.error("ToolbarView: Invalid telemetry status: " + str(status))
 def _sample_worker(self):
     while self._running.is_set():
         try:
             self._send_sample()
             sleep(self.SAMPLE_INTERVAL)
         except Exception as e:
             Logger.error("TelemetryConnection: error sending sample: " + str(e))
Пример #30
0
    def _connection_thread_message_writer(self, tx_queue, connection, should_run):
        """This method is designed to be run in a thread, it will loop infinitely as long as should_run.is_set()
        returns True. In its loop it will attempt to write pending data from the socket connection

        :param tx_queue Queue for pulling data to be written to the socket
        :param connection Socket connection to write data to
        :param should_run Event to check on each loop to determine if to continue writing
        :type tx_queue threading.Queue
        :type connection SocketConnection
        :type should_run threading.Event
        :return: None
        """
        Logger.info('SocketComm: connection thread message writer started')
        while should_run.is_set():
            try:
                message = tx_queue.get(True, 1.0)
                if message:
                    Logger.debug("SocketComm: writing message {}".format(message))
                    connection.write(message)
            except Empty:
                pass
            except Exception as e:
                Logger.error('SocketComm: Exception in connection_thread_message_writer ' + str(e))
                Logger.debug(traceback.format_exc())
                should_run.clear()
                sleep(0.5)
        Logger.debug('SocketComm: connection thread message writer exited')
Пример #31
0
 def bar_value(self, value):
     if self.min <= value <= self.max:
         self.bar_value_percent = self._convert_to_percent(value)
     else:
         Logger.error('ERROR: value < min OR value > max. Try Again.')
Пример #32
0
from sys import platform
from os import environ
from functools import wraps, partial
from kivy.context import register_context
from kivy.config import Config
from kivy.logger import Logger
from kivy.compat import clock as _default_time, PY2
import time

try:
    from kivy._clock import CyClockBase, ClockEvent, FreeClockEvent, \
        CyClockBaseFree
except ImportError:
    Logger.error(
        'Clock: Unable to import kivy._clock. Have you perhaps forgotten to '
        'compile kivy? Kivy contains Cython code which needs to be compiled. '
        'A missing kivy._clock often indicates the Cython code has not been '
        'compiled. Please follow the installation instructions and make sure '
        'to compile Kivy')
    raise

try:
    from multiprocessing import Event as MultiprocessingEvent
except ImportError:  # https://bugs.python.org/issue3770
    from threading import Event as MultiprocessingEvent
from threading import Event as ThreadingEvent

# some reading: http://gameprogrammingpatterns.com/game-loop.html


def _get_sleep_obj():
    pass
Пример #33
0
        new_dir = path.dirname(app_path)
        new_file = path.basename(app_path)
        os.chdir(new_dir)
        new_module_name = path.splitext(new_file)[0]
        if new_module_name not in sys.modules:
            new_module = importlib.import_module(new_module_name)
        else:
            importlib.reload(sys.modules[new_module_name])


if __name__ == "__main__":
    should_run = True
    while should_run:
        if App.get_running_app() is not None:
            App.get_running_app().stop()
        kc = KivyCreator()
        kc.run()
        # Main app stops
        if kc.run_user_app:
            try:
                Logger.info("KC: Running user's app")
                run_from_file(kc.user_app_path)
            except:
                Logger.error(
                    f"KC: An error occurred while running an user app:")
                traceback.print_exc()

            Logger.info("KC: Running main app")
            continue
        should_run = False
Пример #34
0
    def create(outname, filenames, size, padding=1):
        '''This method can be used to create manually an atlas from a set of
        images.

        :Parameters:
            `outname`: str
                Basename to use for ``.atlas`` creation and ``-<idx>.png``
                associated images.
            `filenames`: list
                List of filename to put in the atlas
            `size`: int
                Size of an atlas image
            `padding`: int, default to 1
                Padding to put around each image. Care, if you put 0, they might
                be some issues with OpenGL, because by default, Kivy texture are
                using GL_CLAMP_TO_EDGE, and the edge is another image than
                the image you'll want to display.
        '''
        # Thanks to
        # omnisaurusgames.com/2011/06/texture-atlas-generation-using-python/
        # for its initial implementation.
        try:
            import Image
        except ImportError:
            Logger.critical('Atlas: Imaging/PIL are missing')
            raise

        size = int(size)

        # open all of the images
        ims = [(f, Image.open(f)) for f in filenames]

        # sort by image area
        ims = sorted(ims,
                     key=lambda im: im[1].size[0] * im[1].size[1],
                     reverse=True)

        # free boxes are empty space in our output image set
        # the freebox tuple format is: outidx, x, y, w, h
        freeboxes = [(0, 0, 0, size, size)]
        numoutimages = 1
        padding = 1

        # full boxes are areas where we have placed images in the atlas
        # the full box tuple format is: image, outidx, x, y, w, h, filename
        fullboxes = []

        # do the actual atlasing by sticking the largest images we can have into
        # the smallest valid free boxes
        for imageinfo in ims:
            im = imageinfo[1]
            imw, imh = im.size
            imw += padding
            imh += padding
            if imw > size or imh > size:
                Logger.error('Atlas: image %s is larger than the atlas size!'%\
                    imageinfo[0])
                return

            inserted = False
            while not inserted:
                for idx, fb in enumerate(freeboxes):
                    # find the smallest free box that will contain this image
                    if fb[3] >= imw and fb[4] >= imh:
                        # we found a valid spot! Remove the current freebox, and
                        # split the leftover space into (up to) two new
                        # freeboxes
                        del freeboxes[idx]
                        if fb[3] > imw:
                            freeboxes.append(
                                (fb[0], fb[1] + imw, fb[2], fb[3] - imw, imh))

                        if fb[4] > imh:
                            freeboxes.append((fb[0], fb[1], fb[2] + imh, fb[3],
                                              fb[4] - imh))

                        # keep this sorted!
                        freeboxes = sorted(freeboxes,
                                           key=lambda fb: fb[3] * fb[4])
                        fullboxes.append(
                            (im, fb[0], fb[1] + padding, fb[2] + padding,
                             imw - padding, imh - padding, imageinfo[0]))
                        inserted = True
                        break

                if not inserted:
                    # oh crap - there isn't room in any of our free boxes, so we
                    # have to add a new output image
                    freeboxes.append((numoutimages, 0, 0, size, size))
                    numoutimages += 1

        # now that we've figured out where everything goes, make the output
        # images and blit the source images to the approriate locations
        Logger.info('Atlas: create an {0}x{0} rgba image'.format(size))
        outimages = [
            Image.new('RGBA', (size, size))
            for i in range(0, int(numoutimages))
        ]
        for fb in fullboxes:
            outimages[fb[1]].paste(fb[0], (fb[2], fb[3]))

        # save the output images
        for idx, outimage in enumerate(outimages):
            outimage.save('%s-%d.png' % (outname, idx))

        # write out an json file that says where everything ended up
        meta = {}
        for fb in fullboxes:
            fn = '%s-%d.png' % (basename(outname), fb[1])
            if fn not in meta:
                d = meta[fn] = {}
            else:
                d = meta[fn]

            # fb[6] contain the filename aka '../apok.png'. just get only 'apok'
            # as the uniq id.
            uid = splitext(basename(fb[6]))[0]
            x, y, w, h = fb[2:6]
            d[uid] = x, size - y - h, w, h

        outfn = '%s.atlas' % outname
        with open(outfn, 'w') as fd:
            json.dump(meta, fd)

        return outfn, meta
Пример #35
0
        def __init__(self, device, args):
            super(MTDMotionEventProvider, self).__init__(device, args)
            self._device = None
            self.input_fn = None
            self.default_ranges = dict()

            # split arguments
            args = args.split(',')
            if not args:
                Logger.error('MTD: No filename pass to MTD configuration')
                Logger.error('MTD: Use /dev/input/event0 for example')
                return None

            # read filename
            self.input_fn = args[0]
            Logger.info('MTD: Read event from <%s>' % self.input_fn)

            # read parameters
            for arg in args[1:]:
                if arg == '':
                    continue
                arg = arg.split('=')

                # ensure it's a key = value
                if len(arg) != 2:
                    err = 'MTD: Bad parameter %s: Not in key=value format' %\
                        arg
                    Logger.error(err)
                    continue

                # ensure the key exist
                key, value = arg
                if key not in MTDMotionEventProvider.options:
                    Logger.error('MTD: unknown %s option' % key)
                    continue

                # ensure the value
                try:
                    self.default_ranges[key] = int(value)
                except ValueError:
                    err = 'MTD: invalid value %s for option %s' % (key, value)
                    Logger.error(err)
                    continue

                # all good!
                Logger.info('MTD: Set custom %s to %d' % (key, int(value)))

            if 'rotation' not in self.default_ranges:
                self.default_ranges['rotation'] = 0
            elif self.default_ranges['rotation'] not in (0, 90, 180, 270):
                Logger.error('HIDInput: invalid rotation value ({})'.format(
                    self.default_ranges['rotation']))
                self.default_ranges['rotation'] = 0
Пример #36
0
                    type=str,
                    help="Mail of the author of the project")
parser.add_argument("-site", type=str, help="Project site")

SITE_PROJECT = parser.parse_args().site
VERSION_PROJECT = parser.parse_args().version
COPYRIGHT_PROJECT = parser.parse_args().copyright
NAME_PROJECT = parser.parse_args().name
DIR_PROJECT = parser.parse_args().path
REPO_PROJECT = parser.parse_args().repo
NAME_AUTHOR = parser.parse_args().author
ADDRESS_MAIL = parser.parse_args().mail
FULL_PATH_TO_PROJECT = os.path.join(DIR_PROJECT, NAME_PROJECT)

if os.path.exists(FULL_PATH_TO_PROJECT):
    Logger.error("Project {} already exists!".format(NAME_PROJECT))
    sys.exit(0)

try:
    os.makedirs(FULL_PATH_TO_PROJECT)
    Logger.info(
        "Created project directory {} ...".format(FULL_PATH_TO_PROJECT))
except FileNotFoundError:
    Logger.error(
        "The specified {} directory does not exist!".format(DIR_PROJECT))
except Exception:
    print(traceback.format_exc())
    Logger.error("You are not authorized to create a project in "
                 "{} directory!".format(DIR_PROJECT))

try:
Пример #37
0
    def create(outname, filenames, size, padding=2, use_path=False):
        '''This method can be used to create manually an atlas from a set of
        images.

        :Parameters:
            `outname`: str
                Basename to use for ``.atlas`` creation and ``-<idx>.png``
                associated images.
            `filenames`: list
                List of filename to put in the atlas
            `size`: int
                Size of an atlas image
            `padding`: int, default to 2
                Padding to put around each image.

                Be careful. If you're using a padding < 2, you might get issues
                with border of the images. Because of the OpenGL linearization,
                it might take the pixels of the adjacent image.

                If you're using a padding >= 2, we'll automatically generate a
                "border" of 1px of your image, around the image. If you look at
                the result, don't be scared if the image inside it are not
                exactly the same as yours :).
            `use_path`: bool, if true, the relative path of the source png
                file names will be included in their atlas ids, rather
                that just the file name. Leading dots and slashes will be
                excluded and all other slashes in the path will be replaced
                with underscores, so for example, if the path and file name is
                ``../data/tiles/green_grass.png`` then the id will be
                ``green_grass`` if use_path is False, and it will be
                ``data_tiles_green_grass`` if use_path is True

            .. versionchanged:: 1.8.0
                Parameter use_path added
        '''
        # Thanks to
        # omnisaurusgames.com/2011/06/texture-atlas-generation-using-python/
        # for its initial implementation.
        try:
            from PIL import Image
        except ImportError:
            Logger.critical('Atlas: Imaging/PIL are missing')
            raise

        size = int(size)

        # open all of the images
        ims = [(f, Image.open(f)) for f in filenames]

        # sort by image area
        ims = sorted(ims,
                     key=lambda im: im[1].size[0] * im[1].size[1],
                     reverse=True)

        # free boxes are empty space in our output image set
        # the freebox tuple format is: outidx, x, y, w, h
        freeboxes = [(0, 0, 0, size, size)]
        numoutimages = 1

        # full boxes are areas where we have placed images in the atlas
        # the full box tuple format is: image, outidx, x, y, w, h, filename
        fullboxes = []

        # do the actual atlasing by sticking the largest images we can have into
        # the smallest valid free boxes
        for imageinfo in ims:
            im = imageinfo[1]
            imw, imh = im.size
            imw += padding
            imh += padding
            if imw > size or imh > size:
                Logger.error('Atlas: image %s is larger than the atlas size!' %
                             imageinfo[0])
                return

            inserted = False
            while not inserted:
                for idx, fb in enumerate(freeboxes):
                    # find the smallest free box that will contain this image
                    if fb[3] >= imw and fb[4] >= imh:
                        # we found a valid spot! Remove the current freebox, and
                        # split the leftover space into (up to) two new
                        # freeboxes
                        del freeboxes[idx]
                        if fb[3] > imw:
                            freeboxes.append(
                                (fb[0], fb[1] + imw, fb[2], fb[3] - imw, imh))

                        if fb[4] > imh:
                            freeboxes.append((fb[0], fb[1], fb[2] + imh, fb[3],
                                              fb[4] - imh))

                        # keep this sorted!
                        freeboxes = sorted(freeboxes,
                                           key=lambda fb: fb[3] * fb[4])
                        fullboxes.append(
                            (im, fb[0], fb[1] + padding, fb[2] + padding,
                             imw - padding, imh - padding, imageinfo[0]))
                        inserted = True
                        break

                if not inserted:
                    # oh crap - there isn't room in any of our free boxes, so we
                    # have to add a new output image
                    freeboxes.append((numoutimages, 0, 0, size, size))
                    numoutimages += 1

        # now that we've figured out where everything goes, make the output
        # images and blit the source images to the approriate locations
        Logger.info('Atlas: create an {0}x{0} rgba image'.format(size))
        outimages = [
            Image.new('RGBA', (size, size))
            for i in range(0, int(numoutimages))
        ]
        for fb in fullboxes:
            x, y = fb[2], fb[3]
            out = outimages[fb[1]]
            out.paste(fb[0], (fb[2], fb[3]))
            w, h = fb[0].size
            if padding > 1:
                out.paste(fb[0].crop((0, 0, w, 1)), (x, y - 1))
                out.paste(fb[0].crop((0, h - 1, w, h)), (x, y + h))
                out.paste(fb[0].crop((0, 0, 1, h)), (x - 1, y))
                out.paste(fb[0].crop((w - 1, 0, w, h)), (x + w, y))

        # save the output images
        for idx, outimage in enumerate(outimages):
            outimage.save('%s-%d.png' % (outname, idx))

        # write out an json file that says where everything ended up
        meta = {}
        for fb in fullboxes:
            fn = '%s-%d.png' % (basename(outname), fb[1])
            if fn not in meta:
                d = meta[fn] = {}
            else:
                d = meta[fn]

            # fb[6] contain the filename
            if use_path:
                # use the path with separators replaced by _
                # example '../data/tiles/green_grass.png' becomes
                # 'data_tiles_green_grass'
                uid = splitext(fb[6])[0]
                # remove leading dots and slashes
                uid = uid.lstrip('./\\')
                # replace remaining slashes with _
                uid = uid.replace('/', '_').replace('\\', '_')
            else:
                # for example, '../data/tiles/green_grass.png'
                # just get only 'green_grass' as the uniq id.
                uid = splitext(basename(fb[6]))[0]

            x, y, w, h = fb[2:6]
            d[uid] = x, size - y - h, w, h

        outfn = '%s.atlas' % outname
        with open(outfn, 'w') as fd:
            json.dump(meta, fd)

        return outfn, meta
Пример #38
0
    def auto_detect_worker(self):
        Logger.info('RCPAPI: auto_detect_worker starting')

        class VersionResult(object):
            version_json = None

        def on_ver_win(value, source):
            version_result.version_json = value
            version_result_event.set()

        while self._running.is_set():
            self._auto_detect_event.wait()
            self._auto_detect_event.clear()
            self._enable_autodetect.wait()
            # check again if we're shutting down
            # to prevent a needless re-detection attempt
            if not self._running.is_set():
                break
            try:
                Logger.debug("RCPAPI: Starting auto-detect")
                self._auto_detect_busy.set()
                self.sendCommandLock.acquire()
                self.addListener("ver", on_ver_win)

                comms = self.comms
                if comms and comms.isOpen():
                    comms.close()

                version_result = VersionResult()
                version_result_event = Event()
                version_result_event.clear()

                if comms.device:
                    devices = [comms.device]
                else:
                    devices = comms.get_available_devices()
                    last_known_device = self._settings.userPrefs.get_pref(
                        'preferences', 'last_known_device')
                    # if there was a last known device try it repeatedly while trying the other devices.
                    if last_known_device:
                        Logger.info(
                            'RCPAPI: trying last known device before each other device: {}'
                            .format(last_known_device))
                        # ensure we remove it from the existing list
                        try:
                            devices.remove(last_known_device)
                        except ValueError:
                            pass

                        # rebuild the list, with last_known_device as every second entry
                        temp_list = devices
                        devices = [last_known_device]
                        for device in temp_list:
                            devices = devices + [device, last_known_device]

                    Logger.debug('RCPAPI: Searching for device')

                testVer = VersionConfig()
                for device in devices:
                    try:
                        if not self._running.is_set():
                            break
                        Logger.debug('RCPAPI: Trying ' + str(device))
                        if self.detect_activity_callback:
                            self.detect_activity_callback(str(device))
                        comms.device = device
                        comms.open()
                        self.sendGetVersion()
                        version_result_event.wait(2)
                        version_result_event.clear()
                        if version_result.version_json != None:
                            testVer.fromJson(
                                version_result.version_json.get('ver', None))
                            if testVer.is_valid:
                                break  # we found something!
                        else:
                            try:
                                Logger.debug('RCPAPI: Giving up on ' +
                                             str(device))
                                comms.close()
                            finally:
                                pass

                    except Exception as detail:
                        Logger.error('RCPAPI: Not found on ' + str(device) +
                                     " " + str(detail))
                        Logger.error(traceback.format_exc())
                        try:
                            comms.close()
                        finally:
                            pass

                if testVer.is_valid:
                    Logger.debug("RCPAPI: Found device version " +
                                 str(testVer) + " on port: " +
                                 str(comms.device))
                    self.detect_win(testVer)
                    self._auto_detect_event.clear()
                    self._settings.userPrefs.set_pref('preferences',
                                                      'last_known_device',
                                                      comms.device)
                else:
                    Logger.debug('RCPAPI: Did not find device')
                    comms.close()
                    comms.device = None
                    if self.detect_fail_callback: self.detect_fail_callback()
            except Exception as e:
                Logger.error('RCPAPI: Error running auto detect: ' + str(e))
                Logger.error(traceback.format_exc())
                if self.detect_fail_callback: self.detect_fail_callback()
            finally:
                Logger.debug("RCPAPI: auto detect finished. port=" +
                             str(comms.device))
                self._auto_detect_busy.clear()
                self.removeListener("ver", on_ver_win)
                self.sendCommandLock.release()
                comms.device = None
                sleep(AUTODETECT_COOLOFF_TIME)

        safe_thread_exit()
        Logger.debug('RCPAPI: auto_detect_worker exiting')
Пример #39
0
    def cmd_sequence_worker(self):
        Logger.info('RCPAPI: cmd_sequence_worker starting')
        while self._running.is_set():
            try:
                # Block for 1 second for messages
                command = self._command_queue.get(
                    True, RcpApi.COMMAND_SEQUENCE_TIMEOUT)

                command_list = command.command_list
                rootName = command.rootName
                winCallback = command.winCallback
                failCallback = command.failCallback
                comms = self.comms

                Logger.debug('RCPAPI: Execute Sequence begin')

                if not comms.isOpen(): self.run_auto_detect()

                q = self.cmdSequenceQueue

                responseResults = {}
                cmdCount = 0
                cmdLength = len(command_list)
                self.notifyProgress(cmdCount, cmdLength)
                try:
                    for rcpCmd in command_list:
                        payload = rcpCmd.payload
                        index = rcpCmd.index
                        option = rcpCmd.option
                        last = rcpCmd.last

                        level2Retry = 0
                        name = rcpCmd.name
                        result = None

                        self.addListener(name, self.rcpCmdComplete)
                        while not result and level2Retry <= self.level_2_retries:
                            args = []
                            if payload is not None:
                                args.append(payload)
                            if index is not None:
                                args.append(index)
                            if option is not None:
                                args.append(option)
                            if last is not None:
                                args.append(last)
                            rcpCmd.cmd(*args)
                            retry = 0
                            while not result and retry < DEFAULT_READ_RETRIES:
                                try:
                                    result = q.get(True, self.msg_rx_timeout)
                                    msgName = result.keys()[0]
                                    if not msgName == name:
                                        Logger.warn(
                                            'RCPAPI: rx message did not match expected name '
                                            + str(name) + '; ' + str(msgName))
                                        result = None
                                except Exception as e:
                                    Logger.warn(
                                        'RCPAPI: Read message timeout waiting for {}'
                                        .format(name))
                                    self.recoverTimeout()
                                    retry += 1
                            if not result:
                                Logger.warn('RCPAPI: Level 2 retry for (' +
                                            str(level2Retry) + ') ' + name)
                                level2Retry += 1

                        if not result:
                            raise Exception('Timeout waiting for ' + name)

                        responseResults[name] = result[name]
                        self.removeListener(name, self.rcpCmdComplete)
                        cmdCount += 1
                        self.notifyProgress(cmdCount, cmdLength)

                    if rootName:
                        callback = self.callback_factory(
                            winCallback, {rootName: responseResults})
                    else:
                        callback = self.callback_factory(
                            winCallback, responseResults)

                    Clock.schedule_once(callback)

                except CommsErrorException:
                    self.recover_connection()
                    self.connected_version = None
                except Exception as detail:
                    Logger.error('RCPAPI: Command sequence exception: ' +
                                 str(detail))
                    Logger.error(traceback.format_exc())
                    callback = self.callback_factory(failCallback, detail)
                    Clock.schedule_once(callback)
                    self.connected_version = None
                    self.recover_connection()

                Logger.debug('RCPAPI: Execute Sequence complete')

            except Queue.Empty:
                pass

            except Exception as e:
                Logger.error('RCPAPI: Execute command exception ' + str(e))

        Logger.info('RCPAPI: cmd_sequence_worker exiting')
        safe_thread_exit()
def _make_torrent(message_queue, launcher_basedir, mods):
    """Create torrents from mods on the disk."""

    Logger.info('make_torrent: Starting the torrents creations process...')
    # announces = ['http://{}/announce.php'.format(launcher_config.domain)]
    announces = devmode.get_torrent_tracker_urls()
    web_seeds = devmode.get_torrent_web_seeds()

    if not announces:
        Logger.error('make_torrent: torrent_tracker_urls cannot be empty!')
        message_queue.reject({'msg': 'torrent_tracker_urls cannot be empty!'})
        return

    mods_created = []

    counter = 0
    for mod in mods:
        counter += 1

        if mod.is_complete():
            Logger.info(
                'make_torrent: Mod {} is up to date, skipping...'.format(
                    mod.foldername))
            continue

        Logger.info(
            'make_torrent: Generating new torrent for mod {}...'.format(
                mod.foldername))

        timestamp = manager_functions.create_timestamp(time.time())
        output_file = '{}-{}.torrent'.format(mod.foldername, timestamp)
        output_path = os.path.join(launcher_basedir, output_file)
        comment = '{} dependency on mod {}'.format(
            launcher_config.launcher_name, mod.foldername)

        directory = os.path.join(mod.parent_location, mod.foldername)
        if not os.path.exists(directory):
            Logger.error(
                'make_torrent: Directory does not exist! Skipping. Directory: {}'
                .format(directory))
            continue

        message_queue.progress(
            {'msg': 'Creating file: {}'.format(output_file)},
            counter / len(mods))
        file_created = torrent_utils.create_torrent(directory, announces,
                                                    output_path, comment,
                                                    web_seeds)
        with file(file_created, 'rb') as f:
            mod.torrent_content = f.read()
        mod.torrent_url = '{}{}'.format(_torrent_url_base(), output_file)
        mods_created.append((mod, file_created, output_file, timestamp))
        Logger.info('make_torrent: New torrent for mod {} created!'.format(
            mod.foldername))

    if mods_created:
        mods_user_friendly_list = []
        for mod, _, _, _ in mods_created:
            if hasattr(mod, 'is_launcher'):
                mods_user_friendly_list.append('{} ({})'.format(
                    mod.foldername, get_new_launcher_version(mod)))
            else:
                mods_user_friendly_list.append(mod.foldername)

        message = textwrap.dedent('''
            The following mods have been prepared to be updated:

            {}

            Click OK to upload all those mods to the server.
            If you do not want to upload ALL those mods, close the launcher now.

            After the upload is done, the launcher will start seeding all the new mods.
            You CAN then start and stop the launcher as you wish as long as you
            enabled seeding in OPTIONS!

            Make sure the mods are fully uploaded before you stop seeding for good.
            ''').format('\n'.join(mods_user_friendly_list))

        yield Message.msgbox(message, name='confirm_upload_mods')
        perform_update(message_queue, mods_created)

        for mod, _, _, _ in mods_created:
            torrent_utils.set_torrent_complete(mod)

    message_queue.resolve({
        'msg':
        'Torrents created: {}'.format(len(mods_created)),
        'mods_created':
        len(mods_created)
    })
Пример #41
0
def err(title, text):
    Logger.error(title + ' : ' + text)
Пример #42
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
Пример #43
0
parser.add_argument('-mail', type=str,
                    help='Mail of the author of the project')
parser.add_argument('-site', type=str, help='Project site')

SITE_PROJECT = parser.parse_args().site
VERSION_PROJECT = parser.parse_args().version
COPYRIGHT_PROJECT = parser.parse_args().copyright
NAME_PROJECT = parser.parse_args().name
DIR_PROJECT = parser.parse_args().path
REPO_PROJECT = parser.parse_args().repo
NAME_AUTHOR = parser.parse_args().author
ADDRESS_MAIL = parser.parse_args().mail
FULL_PATH_TO_PROJECT = os.path.join(DIR_PROJECT, NAME_PROJECT)

if os.path.exists(FULL_PATH_TO_PROJECT):
    Logger.error('Project {} already exists!'.format(NAME_PROJECT))
    sys.exit(0)

try:
    os.makedirs(FULL_PATH_TO_PROJECT)
    Logger.info(
        'Created project directory {} ...'.format(FULL_PATH_TO_PROJECT))
except FileNotFoundError:
    Logger.error(
        'The specified {} directory does not exist!'.format(DIR_PROJECT))
except Exception:
    print(traceback.format_exc())
    Logger.error(
        'You are not authorized to create a project in '
        '{} directory!'.format(DIR_PROJECT))
Пример #44
0
    def _run(self):
        app = App.get_running_app()

        try:
            # Open a connection to the Teensy
            if self.hid.open(self.vid, self.pid):

                Logger.info("MPG_rawhid: Connected to HID device %04X:%04X" %
                            (self.vid, self.pid))

                # Infinite loop to read data from the Teensy
                while not self.quit:
                    data = self.hid.recv(timeout=50)
                    if data is not None:
                        size = len(data)
                        if size == 0:
                            continue

                        if not (data[0] == 0x12 and data[1] == 0x34):
                            Logger.error("MPG_rawhid: Not an MPG HID packet")
                            continue

                        axis = data[2]
                        mult = data[3]
                        step = self.twos_comp(data[4], 8)
                        s = data[5]
                        estop = data[6]

                        Logger.debug(
                            "MPG_rawhid: axis: {}, mult: {}, step: {}, speed: {}, estop: {}"
                            .format(axis, mult, step, s, estop))

                        # a= data[7]
                        # b= data[8]
                        # c= data[9]
                        # d= data[10]
                        # us= a<<24 | b<<16 | c << 8 | d
                        # print("us= {}".format(us))

                        if app.is_connected:
                            if estop == 1 and app.status != 'Alarm':
                                app.comms.write('\x18')
                                continue

                        else:
                            continue

                        if app.main_window.is_printing:
                            continue

                        if axis == 0:
                            continue

                        alut = {1: 'X', 2: 'Y', 3: 'Z', 4: 'A'}
                        dist = 0.01 * step * mult
                        if s == 0: s = 1
                        speed = s / 10.0
                        app.comms.write("$J {}{} F{}\n".format(
                            alut[axis], dist, speed))

                # Close the Teensy connection
                self.hid.close()

                Logger.info("MPG_rawhid: Disconnected from HID device")

            else:
                Logger.error(
                    "MPG_rawhid: Failed to open HID device %04X:%04X" %
                    (self.vid, self.pid))

        except:
            Logger.warn("MPG_rawhid: Exception - {}".format(
                traceback.format_exc()))
Пример #45
0
def core_select_lib(category,
                    llist,
                    create_instance=False,
                    base='kivy.core',
                    basemodule=None):
    if 'KIVY_DOC' in os.environ:
        return
    category = category.lower()
    basemodule = basemodule or category
    libs_ignored = []
    errs = []
    for option, modulename, classname in llist:
        try:
            # module activated in config ?
            try:
                if option not in kivy.kivy_options[category]:
                    libs_ignored.append(modulename)
                    Logger.debug(
                        '{0}: Provider <{1}> ignored by config'.format(
                            category.capitalize(), option))
                    continue
            except KeyError:
                pass

            # import module
            mod = __import__(name='{2}.{0}.{1}'.format(basemodule, modulename,
                                                       base),
                             globals=globals(),
                             locals=locals(),
                             fromlist=[modulename],
                             level=0)
            cls = mod.__getattribute__(classname)

            # ok !
            Logger.info('{0}: Provider: {1}{2}'.format(
                category.capitalize(), option,
                '({0} ignored)'.format(libs_ignored) if libs_ignored else ''))
            if create_instance:
                cls = cls()
            return cls

        except ImportError as e:
            errs.append((option, e, sys.exc_info()[2]))
            libs_ignored.append(modulename)
            Logger.debug('{0}: Ignored <{1}> (import error)'.format(
                category.capitalize(), option))
            Logger.trace('', exc_info=e)

        except CoreCriticalException as e:
            errs.append((option, e, sys.exc_info()[2]))
            Logger.error('{0}: Unable to use {1}'.format(
                category.capitalize(), option))
            Logger.error(
                '{0}: The module raised an important error: {1!r}'.format(
                    category.capitalize(), e.message))
            raise

        except Exception as e:
            errs.append((option, e, sys.exc_info()[2]))
            libs_ignored.append(modulename)
            Logger.trace('{0}: Unable to use {1}'.format(
                category.capitalize(), option, category))
            Logger.trace('', exc_info=e)

    err = '\n'.join([
        '{} - {}: {}\n{}'.format(opt, e.__class__.__name__, e,
                                 ''.join(traceback.format_tb(tb)))
        for opt, e, tb in errs
    ])
    Logger.critical(
        '{0}: Unable to find any valuable {0} provider. Please enable '
        'debug logging (e.g. add -d if running from the command line, or '
        'change the log level in the config) and re-run your app to '
        'identify potential causes\n{1}'.format(category.capitalize(), err))
Пример #46
0
platform = core_platform
filesize_units = ('B', 'KB', 'MB', 'GB', 'TB')

_have_win32file = False
if platform == 'win':
    # Import that module here as it's not available on non-windows machines.
    # See http://bit.ly/i9klJE except that the attributes are defined in
    # win32file not win32com (bug on page).
    # Note: For some reason this doesn't work after a os.chdir(), no matter to
    #       what directory you change from where. Windows weirdness.
    try:
        from win32file import FILE_ATTRIBUTE_HIDDEN, GetFileAttributesExW, error
        _have_win32file = True
    except ImportError:
        Logger.error('filechooser: win32file module is missing')
        Logger.error('filechooser: we cant check if a file is hidden or not')


def alphanumeric_folders_first(files, filesystem):
    return (sorted(f for f in files if filesystem.is_dir(f)) +
            sorted(f for f in files if not filesystem.is_dir(f)))


class FileSystemAbstract(object):
    '''Class for implementing a File System view that can be used with the
    :class:`FileChooser`.:attr:`~FileChooser.file_system`.

    .. versionadded:: 1.8.0
    '''
Пример #47
0
    def calculate_size(self):
        from utils import alert
        Logger.info('Printing with mode %s' % str(self.mode))
        alert('Calculating Size for mode %s' % str(self.mode))
        #Create all the necessary steps for while loop in printing
        #populate self.index with line made of i, row, col, face & item
        from datetime import date
        from os.path import split, relpath
        from conf import gamepath
        if self.dst.startswith(gamepath):
            title = relpath(self.dst, gamepath)
        else:
            title = split(self.dst)[-1]
        self.banner = "File: %s - Date : %s -  Print Mode: %s" % (
            title, date.today(), self.mode)
        if self.mode not in ('LAYOUT', 'BINCAN'):
            if self.mode == 'FORCED':
                from conf import card_format
                _w, _h = card_format.size
            else:
                _w, _h = self.mode
            ft = "%.2fcmx%.2fcm" % (_w / cm(1), _h / cm(1))
            self.banner += ' - Format : %s' % ft
        self.pdf.drawString(20, 20, self.banner)
        fps, bps = self.stack
        #Swtich on Print Mode
        if self.mode == 'LAYOUT':
            dst = [(obj.layout[-1], 0, 0, 'F', obj) for obj in fps]
            dst.extend([(obj.layout[-1], 0, 0, 'F', obj) for obj in bps])
            self.index = sorted(dst, key=lambda x: x[0])
            self.index.reverse()
        elif self.mode == 'BINCAN':
            #######################################################
            from conf import page_format
            from layout import BinCanNode
            SIZE = page_format.width - page_format.left - page_format.right, page_format.height - page_format.top - page_format.bottom
            INDEX_PAGE = 0
            dual_dict = dict()
            fg = [(f, i) for (i, f) in enumerate(fps)]
            for f, b in zip(fps, bps):
                dual_dict[f] = b
            #fill current page with what you can
            def skey(item):
                w, h = item[0].getSize()
                return w * h, -item[1]

            fg = sorted(fg, key=skey, reverse=True)
            while fg:
                sorted_phs = fg[:]
                added_ones = list()
                PAGE_LAYOUT = BinCanNode(0, 0, SIZE[0], SIZE[1])
                for f, i in sorted_phs:
                    w, h = f.getSize()
                    layout = PAGE_LAYOUT.find(f, w, h)
                    if not layout:
                        continue
                    del fg[fg.index((f, i))]
                    X, Y = layout.x, layout.y
                    #Rebase properly
                    x = X + page_format.left
                    y = page_format.height - page_format.top - Y - h
                    angle = layout.retry.get(f, 0) * 90
                    self.index.append(
                        (INDEX_PAGE, 0, 0, 'F', (x, y, w, h, angle, f)))
                    added_ones.append((f, (x, y, w, h, angle)))
                if not added_ones:  #We could NOT feet any of the pictures: raise error:
                    Logger.error(
                        'Error: not all pictures could be fit inside one page')
                    break
                if dual_dict:
                    #First page is done, create dual
                    INDEX_PAGE += 1
                    for f, _layout in added_ones:
                        b = dual_dict[f]
                        x, y, w, h, angle = _layout
                        x = page_format.width - page_format.right - x - w
                        angle = -angle
                        self.index.append(
                            (INDEX_PAGE, 0, 0, 'F', (x, y, w, h, angle, b)))
                #Add a new page, only if necessay:
                if fg:
                    INDEX_PAGE += 1
            self.index.reverse()
            ######################################################
        else:
            if self.mode == 'FORCED':
                fitting_size = card_format.size
            else:
                fitting_size = self.mode
            #First determinez the number of item per page, acconirding to the dimensions
            x, y = self.x, self.y = Vector(fitting_size) / cm(1)
            NUM_COL = int((width - left) / (x + 5 / cm(1)))
            NUM_ROW = int((height - top) / (y + 5 / cm(1)))
            PICT_BY_SHEET = NUM_COL * NUM_ROW
            if not (fps) and not (bps):
                print 'Warning: nothing to print: cancelling PDF generation'
                return

            if not NUM_COL or not NUM_ROW:
                PICT_BY_SHEET = 1
                if not NUM_ROW:
                    NUM_ROW = 1
                if not NUM_COL:
                    NUM_COL = 1
                x = self.x = width - left - right
                y = self.y = height - top - bottom

            if 0:
                print 'fitting size', fitting_size
                print "x,y", x, y
                print 'Num row', NUM_ROW
                print 'Num Col', NUM_COL
                print PICT_BY_SHEET, 'pictures by sheet'

            #Now prepare the whole list of index that will be used for the while loop

            index = self.index
            for i in range((len(fps) / PICT_BY_SHEET) + 1):
                for row in range(NUM_ROW):
                    for col in range(NUM_COL):
                        try:
                            obj = fps.pop()
                            index.append((i, row, col, 'F', obj))
                        except IndexError:
                            break
                for row in range(NUM_ROW):
                    for col in range(NUM_COL):
                        try:
                            obj = bps.pop()
                            index.append((i, row, col, 'B', obj))
                        except IndexError:
                            break
            self.index.reverse()
Пример #48
0
def handle_win_lib_import_error(category, provider, mod_name):
    if sys.platform != 'win32':
        return

    assert mod_name.startswith('kivy.')
    kivy_root = os.path.dirname(kivy.__file__)
    dirs = mod_name[5:].split('.')
    mod_path = os.path.join(kivy_root, *dirs)

    # get the full expected path to the compiled pyd file
    # filename is <debug>.cp<major><minor>-<platform>.pyd
    # https://github.com/python/cpython/blob/master/Doc/whatsnew/3.5.rst
    if hasattr(sys, 'gettotalrefcount'):  # debug
        mod_path += '._d'
    mod_path += '.cp{}{}-{}.pyd'.format(
        sys.version_info.major, sys.version_info.minor,
        sysconfig.get_platform().replace('-', '_'))

    # does the compiled pyd exist at all?
    if not os.path.exists(mod_path):
        Logger.debug(
            '{}: Failed trying to import "{}" for provider {}. Compiled file '
            'does not exist. Have you perhaps forgotten to compile Kivy, or '
            'did not install all required dependencies?'.format(
                category, provider, mod_path))
        return

    # tell user to provide dependency walker
    env_var = 'KIVY_{}_DEPENDENCY_WALKER'.format(provider.upper())
    if env_var not in os.environ:
        Logger.debug(
            '{0}: Failed trying to import the "{1}" provider from "{2}". '
            'This error is often encountered when a dependency is missing,'
            ' or if there are multiple copies of the same dependency dll on '
            'the Windows PATH and they are incompatible with each other. '
            'This can occur if you are mixing installations (such as different'
            ' python installations, like anaconda python and a system python) '
            'or if another unrelated program added its directory to the PATH. '
            'Please examine your PATH and python installation for potential '
            'issues. To further troubleshoot a "DLL load failed" error, '
            'please download '
            '"Dependency Walker" (64 or 32 bit version - matching your python '
            'bitness) from dependencywalker.com and set the environment '
            'variable {3} to the full path of the downloaded depends.exe file '
            'and rerun your application to generate an error report'.format(
                category, provider, mod_path, env_var))
        return

    depends_bin = os.environ[env_var]
    if not os.path.exists(depends_bin):
        raise ValueError('"{}" provided in {} does not exist'.format(
            depends_bin, env_var))

    # make file for the resultant log
    fd, temp_file = tempfile.mkstemp(
        suffix='.dwi',
        prefix='kivy_depends_{}_log_'.format(provider),
        dir=os.path.expanduser('~/'))
    os.close(fd)

    Logger.info('{}: Running dependency walker "{}" on "{}" to generate '
                'troubleshooting log. Please wait for it to complete'.format(
                    category, depends_bin, mod_path))
    Logger.debug('{}: Dependency walker command is "{}"'.format(
        category, [depends_bin, '/c', '/od:{}'.format(temp_file), mod_path]))

    try:
        subprocess.check_output(
            [depends_bin, '/c', '/od:{}'.format(temp_file), mod_path])
    except subprocess.CalledProcessError as exc:
        if exc.returncode >= 0x00010000:
            Logger.error(
                '{}: Dependency walker failed with error code "{}". No '
                'error report was generated'.format(category, exc.returncode))
            return

    Logger.info(
        '{}: dependency walker generated "{}" containing troubleshooting '
        'information about provider {} and its failing file "{} ({})". You '
        'can open the file in dependency walker to view any potential issues '
        'and troubleshoot it yourself. '
        'To share the file with the Kivy developers and request support, '
        'please contact us at our support channels '
        'https://kivy.org/doc/master/contact.html (not on github, unless '
        'it\'s truly a bug). Make sure to provide the generated file as well '
        'as the *complete* Kivy log being printed here. Keep in mind the '
        'generated dependency walker log file contains paths to dlls on your '
        'system used by kivy or its dependencies to help troubleshoot them, '
        'and these paths may include your name in them. Please view the '
        'log file in dependency walker before sharing to ensure you are not '
        'sharing sensitive paths'.format(category, temp_file, provider,
                                         mod_name, mod_path))
Пример #49
0
 def _init_presets_error(self, details):
     Logger.error(
         'RaceCaptureApp: Error initializing presets: {}'.format(details))
Пример #50
0
 def on_read_config_error(self, detail):
     self.showActivity("Error reading configuration")
     toast("Error reading configuration. Check your connection",
           length_long=True)
     Logger.error("RaceCaptureApp:Error reading configuration: {}".format(
         str(detail)))
Пример #51
0
              length_long=True)


if __name__ == '__main__':

    class CrashHandler(ExceptionHandler):
        def handle_exception(self, exception_info):
            if type(exception_info) == KeyboardInterrupt:
                Logger.info("CrashHander: KeyboardInterrupt")
                App.get_running_app().stop()
            Logger.critical("CrashHandler: Caught exception in Kivy loop: " +
                            str(exception_info))
            Logger.critical(traceback.format_exc())
            if 'sentry_client' in globals():
                ident = sentry_client.captureException(value=exception_info)
                Logger.critical("CrashHandler: crash caught: Reference is %s" %
                                ident)
            return ExceptionManager.PASS

    ExceptionManager.add_handler(CrashHandler())
    try:
        RaceCaptureApp().run()
    except:
        if 'sentry_client' in globals():
            ident = sentry_client.captureException()
            Logger.error("RaceCaptureApp:crash caught: Reference is %s" %
                         ident)
            Logger.critical(traceback.format_exc())
        else:
            raise
Пример #52
0
 def _init_tracks_error(self, details):
     Logger.error(
         'RaceCaptureApp: Error initializing tracks: {}'.format(details))
Пример #53
0
 def on_new_intent(intent):
     Logger.info("PythonHere: on_new_intent")
     restart_app(get_startup_script(intent))
     Logger.error("PythonHere: app was not restarted")
Пример #54
0
def unzip_extensions():
    '''Unzips Kivy extensions. Internal usage only: don't use it yourself unless
    you know what you're doing and really want to trigger installation of new
    extensions.

    For your file to be recognized as an extension, it has to fulfil a few
    requirements:

     * We require that the file has the ``*.kex`` extension to make the
       distinction between a Kivy extension and an ordinary zip file clear.

     * We require that the ``*.kex`` extension files be put into any of the
       directories listed in EXTENSION_PATHS which is normally
       ~/.kivy/extensions and extensions/ inside kivy's base directory. We do
       not look for extensions on sys.path or elsewhere in the system.

     * We require that the Kivy extension is zipped in a way so that Python's
       zipfile module can extract it properly.

     * We require that the extension internally obeys the common Kivy extension
       format, which looks like this::

            |-- myextension/
                |-- __init__.py
                |-- data/

       The ``__init__.py`` file is the main entrypoint to the extension. All
       names that should be usable when the extension is loaded need to be
       exported (i.e. made available) in the namespace of that file.

       How the extension accesses the code of the library that it wraps (be it
       pure Python or binary code) is up to the extension. For example there
       could be another Python module adjacent to the ``__init__.py`` file from
       which the ``__init__.py`` file imports the usable names that it wants to
       expose.

     * We require that the version of the extension be specified in the
       ``setup.py`` file that is created by the Kivy extension wizard and that
       the version specification format as explained in :func:`~kivy.ext.load`
       be used.
    '''
    Logger.debug('Searching for new extension in %s' % EXTENSION_PATHS)

    for epath in EXTENSION_PATHS:
        if not isdir(epath):
            try:
                mkdir(epath)
            except OSError:
                continue
            files = []
        else:
            files = listdir(epath)
        for zipfn in glob(join(epath, '*.kex')):
            # ZipFile only became a context manager in python 2.7...
            # with ZipFile(zipfn, 'r') as zipf:
            # fail = is_invalid = False
            try:
                zipf = ZipFile(zipfn)
                # /path/to/MyExt-1.0.linux-x86_64.zip
                # /path/to/MyExt-1.0.macos-10.6-x86_64.zip
                extname = zipfn.rsplit(sep)[-1][:-4]
                # MyExt-1.0.linux-x86_64
                # MyExt-1.0.macosx-10.6-x86_64
                t = extname.split('-')
                extname = t[0]
                version = '-'.join(t[1:])
                version = '.'.join(version.split('.')[:2])

                extdir = extname + '_' + version

                # is_invalid = not _is_valid_ext_name(extdir)
            except IOError:
                Logger.warn("Malformed zipfile '%s'! Skipping it." % zipfn)
                continue
            except Exception as e:
                Logger.warn("Malformed extension '%s'! Skipping it." % zipfn)
                zipf.close()
                continue

            already_unzipped = False
            if extdir in files:
                Logger.trace(("Extension '%s' has already been " % extname) +
                             "extracted manually, just moving the zip.")
                already_unzipped = True

            # Filter the namelist of zipfile to take only the members that start
            # with the extension name (MyExt/...)
            members = [
                x for x in zipf.namelist() if x.startswith(extname + '/')
            ]

            if not already_unzipped:
                # Unzip the extension
                try:
                    cache_directories = []
                    mkdir(join(epath, extdir))
                    # I know that there is zipf.extract() and zipf.extractall(),
                    # but on OSX, Python 2.6 is the default and in that version,
                    # both methods have a bug. Fixed in 2.7 only. So use this
                    # workaround until apple upgrades its python. See
                    # http://bugs.python.org/issue4710
                    for member in members:
                        # In zipfiles, folders always end with '/' regardless
                        # of the OS
                        mempath = join(epath, extdir, member)
                        directory = dirname(mempath)
                        if not directory in cache_directories:
                            cache_directories.append(directory)
                            if not exists(directory):
                                mkdir(join(epath, extdir, directory))
                        with open(join(epath, extdir, member), 'wb') as fd:
                            fd.write(zipf.read(member))
                except Exception as e:
                    # Catch any error, e.g. non-writable directory, etc.
                    Logger.error("Failed installing extension " + "'%s' %s." %
                                 (extname, e))
                    return
                finally:
                    zipf.close()
                Logger.info("Installed extension '%s'." % extname)

            # Move the zip out of the way so that it won't be installed again
            # The user can just delete it, but we'll keep it around in case the
            # user needs it again.
            consumed_dir = join(epath, '_consumed_zips')
            if not isdir(consumed_dir):
                mkdir(consumed_dir)
            move(zipfn, consumed_dir)
Пример #55
0
 def _set_bu(self, value):
     try:
         self.electrum_config.set_key('base_unit', value, True)
     except AttributeError:
         Logger.error('Electrum: Config not set '
                      'While trying to save value to config')
Пример #56
0
 def _set_decimal(self, value):
     try:
         self.electrum_config.set_key('decimal_point', value, True)
     except AttributeError:
         Logger.error('Electrum: Config not set '
                      'While trying to save value to config')
Пример #57
0
    def load_first_page(self, *args):
        if user := self.db.get_user():
            self.main_page = page = MainPage()
            self.nav_drawer.type = 'modal'

            self.playlist = self.db.get_playlist()
            self.favorites = self.db.get_favorites()
            if user['dark_mode']:
                self.theme_cls.theme_style = "Dark"
            else:
                self.theme_cls.theme_style = "Light"
            self.genres = user['genres']
            self.artists = user['artists']
            self.volume = user['volume']
            self.play_mode = user['play_mode']

            # load song
            song = self.playlist.current_track
            self.main_page.edit_ui_for_song(song)

            # adding screens
            main_screen = Screen(name='main_page')
            main_screen.add_widget(page)
            self.screen_manager.add_widget(main_screen)
            self.screen_manager.switch_to(main_screen)

            def set_pos(value):
                Logger.debug('SONG: pos %s', value)
                app.song.last_pos = value

            def set_state(value):
                Logger.debug('SONG: state %s', value)
                app.main_page.play_button.check_end()

            # Activity OSC Server
            try:
                activity_port = get_open_port()
            except Exception as e:
                Logger.error(("OSC: Couldn't get open port for activity."
                              "Setting 4999 instead. %s"), e)
                activity_port = 4999
            Logger.debug('ACTIVITY PORT: %s', activity_port)
            self.song = ServerSong(self,
                                   pos_callback=set_pos,
                                   state_callback=set_state,
                                   port=activity_port)

            # Start service
            try:
                service_port = get_open_port()
            except Exception as e:
                Logger.error(("OSC: Couldn't get open port for service."
                              "Setting 5000 instead. %s"), e)
                service_port = 5000
            Logger.debug('SERVICE PORT: %s', service_port)
            if platform == 'android':
                Logger.debug('ACTIVITY: Starting service.')
                args = [str(x) for x in self.song.getaddress()]
                args.append(str(service_port))
                argument = ",".join(args)
                start_service(argument)
                Logger.debug('ACTIVITY: Service started.')
            else:
                from threading import Thread
                from time import sleep
                from service import start_debug_server
                t = Thread(target=start_debug_server,
                           args=(
                               self.song.getaddress(),
                               service_port,
                           ))
                t.daemon = True
                t.start()
                sleep(1)  # allow debug server to finish setting up
            self.song.server_address = [
                self.song.getaddress()[0], service_port
            ]

            # Update UI
            self.play_button.load_song(song)
            self.song.last_pos = user['last_pos']
            slider = self.main_page.ids.playback_slider
            slider.seek(slider, None, value=self.song.last_pos)
            self.main_page.ids.track_current.text = str(
                timedelta(seconds=slider.value))[3:7]

            volume_slider = self.main_page.ids.volume_slider
            volume_slider.value = volume_slider.last_value = self.volume * 100

            Clock.schedule_once(lambda *args, song=song: self.complete_ui())
Пример #58
0
 def _set_num_zeros(self):
     try:
         self.electrum_config.set_key('num_zeros', value, True)
     except AttributeError:
         Logger.error('Electrum: Config not available '
                      'While trying to save value to config')
Пример #59
0
 def __init__(self, device, args):
     super().__init__(device, args)
     args = args.split(',')
     if len(args) == 0:
         Logger.error('Tuio: Invalid configuration for TUIO provider')
         Logger.error('Tuio: Format must be ip:port (eg. 127.0.0.1:3333)')
         err = 'Tuio: Current configuration is <%s>' % (str(','.join(args)))
         Logger.error(err)
         return
     ipport = args[0].split(':')
     if len(ipport) != 2:
         Logger.error('Tuio: Invalid configuration for TUIO provider')
         Logger.error('Tuio: Format must be ip:port (eg. 127.0.0.1:3333)')
         err = 'Tuio: Current configuration is <%s>' % (str(','.join(args)))
         Logger.error(err)
         return
     self.ip, self.port = args[0].split(':')
     self.port = int(self.port)
     self.handlers = {}
     self.oscid = None
     self.tuio_event_q = deque()
     self.touches = {}
Пример #60
0
 def error(self, text, duration=DEFAULT_INFO_DURATION):
     text = str(text)
     Logger.error('{}: {}'.format(get_caller(), text))
     self.error_stack.append(
         Message(text=text, duration=duration, type='error', weak=False))
     self._update()