def __init__(self, **kwargs): # XXX move to style.kv if 'size_hint' not in kwargs: if 'size_hint_x' not in kwargs: self.size_hint_x = None if 'size_hint_y' not in kwargs: self.size_hint_y = None if 'size' not in kwargs: if 'width' not in kwargs: self.width = 700 if 'height' not in kwargs: self.height = 200 if 'scale_min' not in kwargs: self.scale_min = .4 if 'scale_max' not in kwargs: self.scale_max = 1.6 if 'docked' not in kwargs: self.docked = False layout_mode = self._trigger_update_layout_mode = Clock.create_trigger( self._update_layout_mode) layouts = self._trigger_load_layouts = Clock.create_trigger( self._load_layouts) layout = self._trigger_load_layout = Clock.create_trigger( self._load_layout) fbind = self.fbind fbind('docked', self.setup_mode) fbind('have_shift', layout_mode) fbind('have_capslock', layout_mode) fbind('have_special', layout_mode) fbind('layout_path', layouts) fbind('layout', layout) super(VKeyboard, self).__init__(**kwargs) # load all the layouts found in the layout_path directory self._load_layouts() # ensure we have default layouts available_layouts = self.available_layouts if not available_layouts: Logger.critical('VKeyboard: unable to load default layouts') # load the default layout from configuration if self.layout is None: self.layout = Config.get('kivy', 'keyboard_layout') else: # ensure the current layout is found on the available layout self._trigger_load_layout() # update layout mode (shift or normal) self._trigger_update_layout_mode() # create a top layer to draw active keys on with self.canvas: self.background_key_layer = Canvas() self.active_keys_layer = Canvas()
def get_fulldata(self): src = '%s/comiclist' % (self.base_url) try: r = requests.get(src) r.raise_for_status() except HTTPError: Logger.critical('HTTPerror for %s' % src ) else: data = r.json() Logger.debug("get_fulldata started using") 'brake data into sinle comics' for item in data['comics']: comic = CsComic(item) add_update_comic(comic) #get Thumbnails comic._get_cs_thumb() #get Series list src = "%s/entities/series" % (self.base_url) try: r = requests.get(src) r.raise_for_status() except HTTPError: Logger.critical('HTTPerror for %s' % src ) else: print r.json() series_list = r.json() for item in series_list['series']: print item if item is not None: add_series_list(item)
def print_gl_version(): version = glGetString(GL_VERSION) vendor = glGetString(GL_VENDOR) renderer = glGetString(GL_RENDERER) Logger.info('GL: OpenGL version <{0}>'.format(version)) Logger.info('GL: OpenGL vendor <{0}>'.format(vendor)) Logger.info('GL: OpenGL renderer <{0}>'.format(renderer)) # Let the user know if his graphics hardware/drivers are too old major, minor = gl_get_version() Logger.info('GL: OpenGL parsed version: %d, %d' % (major, minor)) if (major, minor) < MIN_REQUIRED_GL_VERSION and not \ bool(int(environ.get('USE_OPENGL_MOCK', 0))): msg = ( 'GL: Minimum required OpenGL version (2.0) NOT found!\n\n' 'OpenGL version detected: {0}.{1}\n\n' 'Version: {2}\nVendor: {3}\nRenderer: {4}\n\n' 'Try upgrading your graphics drivers and/or your ' 'graphics hardware in case of problems.\n\n' 'The application will leave now.').format( major, minor, version, vendor, renderer) Logger.critical(msg) msgbox(msg) if platform != 'android': # XXX in the android emulator (latest version at 22 march 2013), # this call was segfaulting the gl stack. Logger.info('GL: Shading version <{0}>'.format( glGetString(GL_SHADING_LANGUAGE_VERSION))) Logger.info('GL: Texture max size <{0}>'.format( glGetIntegerv(GL_MAX_TEXTURE_SIZE)[0])) Logger.info('GL: Texture max units <{0}>'.format( glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS)[0]))
def print_gl_version(): version = str(glGetString(GL_VERSION)) vendor = str(glGetString(GL_VENDOR)) renderer = str(glGetString(GL_RENDERER)) Logger.info('GL: OpenGL version <%s>' % version) Logger.info('GL: OpenGL vendor <%s>' % vendor) Logger.info('GL: OpenGL renderer <%s>' % renderer) # Let the user know if his graphics hardware/drivers are too old major, minor = gl_get_version() Logger.info('GL: OpenGL parsed version: %d, %d' % (major, minor)) if (major, minor) < MIN_REQUIRED_GL_VERSION: msg = ( 'GL: Minimum required OpenGL version (2.0) NOT found!\n\n' 'OpenGL version detected: {0}.{1}\n\n' 'Version: {2}\nVendor: {3}\nRenderer: {4}\n\n' 'Try upgrading your graphics drivers and/or your ' 'graphics hardware in case of problems.\n\n' 'The application will leave now.').format( major, minor, version, vendor, renderer) Logger.critical(msg) msgbox(msg) Logger.info('GL: Shading version <%s>' % str( glGetString(GL_SHADING_LANGUAGE_VERSION))) Logger.info('GL: Texture max size <%s>' % str( glGetIntegerv(GL_MAX_TEXTURE_SIZE)[0])) Logger.info('GL: Texture max units <%s>' % str( glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS)[0]))
def print_gl_version(): version = str(glGetString(GL_VERSION)) Logger.info("GL: OpenGL version <%s>" % version) Logger.info("GL: OpenGL vendor <%s>" % str(glGetString(GL_VENDOR))) Logger.info("GL: OpenGL renderer <%s>" % str(glGetString(GL_RENDERER))) Logger.info("GL: Shading version <%s>" % str(glGetString(GL_SHADING_LANGUAGE_VERSION))) Logger.info("GL: Texture max size <%s>" % str(glGetIntegerv(GL_MAX_TEXTURE_SIZE)[0])) Logger.info("GL: Texture max units <%s>" % str(glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS)[0])) # As per http://www.opengl.org/resources/faq/technical/extensions.htm # the format for the string is: # """The first part of the return string must be of the form # [major-number].[minor-number], optionally followed by a release # number or other vendor-specific information. try: if version.startswith("OpenGL ES "): version = version[10:] majorminor = version.split()[0] major, minor = majorminor.split(".")[0:2] major, minor = int(major), int(minor) except: # We don't want to bail out here if there is an error while parsing # Just raise a warning (God knows what vendors return here...) Logger.warning("GL: Error parsing OpenGL version: %r" % version) else: # If parsing went without problems, let the user know if his # graphics hardware/drivers are too old if (major, minor) < MIN_REQUIRED_GL_VERSION: msg = ( "GL: Minimum required OpenGL version (2.0) NOT found! " "Try upgrading your graphics drivers and/or your " "graphics hardware in case of problems." ) Logger.critical(msg)
def probe(self): inputs = get_inputs(self.input_path) inputs = [x for x in inputs if x.has_capability(ABS_MT_POSITION_X)] for device in inputs: Logger.info('ProbeSysfs: found device: %s at %s' % ( device.name, device.device)) # must ignore ? if self.match: if not match(self.match, device.name, IGNORECASE): Logger.warning('ProbeSysfs: device not match the' ' rule in config, ignoring.') continue d = device.device devicename = self.device % dict(name=d.split(sep)[-1]) provider = MotionEventFactory.get(self.provider) if provider is None: Logger.info('ProbeSysfs: unable to found provider %s' % self.provider) Logger.info('ProbeSysfs: fallback on hidinput') provider = MotionEventFactory.get('hidinput') if provider is None: Logger.critical('ProbeSysfs: no input provider found' ' to handle this device !') continue instance = provider(devicename, '%s,%s' % (device.device, ','.join(self.args))) if instance: from kivy.base import EventLoop EventLoop.add_input_provider(instance)
def print_gl_version(): version = str(glGetString(GL_VERSION)) Logger.info('GL: OpenGL version <%s>' % version) Logger.info('GL: OpenGL vendor <%s>' % str(glGetString(GL_VENDOR))) Logger.info('GL: OpenGL renderer <%s>' % str(glGetString(GL_RENDERER))) # As per http://www.opengl.org/resources/faq/technical/extensions.htm # the format for the string is: # """The first part of the return string must be of the form # [major-number].[minor-number], optionally followed by a release # number or other vendor-specific information. try: majorminor = version.split()[0] major, minor = majorminor.split('.')[0:2] major, minor = int(major), int(minor) except: # We don't want to bail out here if there is an error while parsing # Just raise a warning (God knows what vendors return here...) Logger.warning('GL: Error parsing OpenGL version: %r' % version) else: # If parsing went without problems, let the user know if his # graphics hardware/drivers are too old if (major, minor) < MIN_REQUIRED_GL_VERSION: msg = 'GL: Minimum required OpenGL version (2.0) NOT found! ' \ 'Try upgrading your graphics drivers and/or your ' \ 'graphics hardware in case of problems.' Logger.critical(msg)
def run(self): """Launches the app in standalone mode. """ if not self.built: self.load_config() self.load_kv(filename=self.options.get("kv_file")) root = self.build() if root: self.root = root if self.root: from kivy.core.window import Window Window.add_widget(self.root) # Check if the window is already created from kivy.base import EventLoop window = EventLoop.window if window: self._app_window = window window.set_title(self.get_application_name()) icon = self.get_application_icon() if icon: window.set_icon(icon) self._install_settings_keys(window) else: Logger.critical("Application: No window is created." " Terminating application run.") return self.dispatch("on_start") runTouchApp() self.stop()
def run(self): '''Launches the app in standalone mode. ''' if not self.built: self.load_config() self.load_kv(filename=self.kv_file) root = self.build() if root: self.root = root if self.root: if not isinstance(self.root, Widget): Logger.critical('App.root must be an _instance_ of Widget') raise Exception('Invalid instance in App.root') from kivy.core.window import Window Window.add_widget(self.root) # Check if the window is already created from kivy.base import EventLoop window = EventLoop.window if window: self._app_window = window window.set_title(self.get_application_name()) icon = self.get_application_icon() if icon: window.set_icon(icon) self._install_settings_keys(window) else: Logger.critical("Application: No window is created." " Terminating application run.") return self.dispatch('on_start') runTouchApp() self.stop()
def _process_events_before_frame(self): found = True count = self.max_iteration events = self._events while found: count -= 1 if count == -1: Logger.critical( "Clock: Warning, too much iteration done before" " the next frame. Check your code, or increase" " the Clock.max_iteration attribute" ) break # search event that have timeout = -1 found = False for cid in list(events.keys())[:]: for event in events[cid][:]: if event.timeout != -1: continue found = True if event.tick(self._last_tick) is False: # event may be already removed by the callback if event in events[cid]: events[cid].remove(event)
def core_select_lib(category, llist, create_instance=False): category = category.lower() for option, modulename, classname in llist: try: # module activated in config ? if option not in kivy.kivy_options[category]: Logger.debug('%s: option <%s> ignored by config' % (category.capitalize(), option)) continue # import module mod = __import__(name='%s.%s' % (category, modulename), globals=globals(), locals=locals(), fromlist=[modulename], level=-1) cls = mod.__getattribute__(classname) # ok ! Logger.info('%s: using <%s> as %s provider' % (category.capitalize(), option, category)) if create_instance: cls = cls() return cls except Exception as e: Logger.warning('%s: Unable to use <%s> as %s' 'provider' % (category.capitalize(), option, category)) Logger.debug('', exc_info = e) Logger.critical('%s: Unable to find any valuable %s provider ' 'at all!' % (category.capitalize(), category.capitalize()))
def _process_events_before_frame(self): found = True count = self.max_iteration events = self._events while found: count -= 1 if count < 0: Logger.critical('Clock: Warning, too much iteration done before' ' the next frame. Check your code, or increase ' 'the Clock.max_iteration attribute') # search event that have timeout = -1 found = False for cid in events.keys()[:]: for event in events[cid][:]: if event.timeout != -1: continue found = True if event.tick(self._last_tick) is False: # event may be already removed by the callback if event in events[cid]: events[cid].remove(event) if count != self.max_iteration - 1: i = self.max_iteration - count + 1 if __debug__: Logger.trace('Clock: we done %d iteration before the frame' % i)
def run(self, kv_file = None): '''Launches the app in standalone mode. ''' if not self.built: self.load_config() self.load_kv(kv_file) root = self.build() if root: self.root = root if self.root: from kivy.core.window import Window Window.add_widget(self.root) # Check if the window is already created from kivy.base import EventLoop window = EventLoop.window if window: self._app_window = window window.set_title(self.get_application_name()) icon = self.get_application_icon() if icon: window.set_icon(icon) self._install_settings_keys(window) else: Logger.critical("Application: No window is created." " Terminating application run.") return self.dispatch('on_start') runTouchApp() self.dispatch('on_stop') # Clear the window children for child in window.children: window.remove_widget(child)
def configure_keyboards(self): # Configure how to provide keyboards (virtual or not) # register system keyboard to listening keys from window sk = self._system_keyboard self.bind( on_key_down=sk._on_window_key_down, on_key_up=sk._on_window_key_up, on_textinput=sk._on_window_textinput) # use the device's real keyboard self.use_syskeyboard = True # use the device's real keyboard self.allow_vkeyboard = False # one single vkeyboard shared between all widgets self.single_vkeyboard = True # the single vkeyboard is always sitting at the same position self.docked_vkeyboard = False # now read the configuration mode = Config.get('kivy', 'keyboard_mode') if mode not in ('', 'system', 'dock', 'multi', 'systemanddock', 'systemandmulti'): Logger.critical('Window: unknown keyboard mode %r' % mode) # adapt mode according to the configuration if mode == 'system': self.use_syskeyboard = True self.allow_vkeyboard = False self.single_vkeyboard = True self.docked_vkeyboard = False elif mode == 'dock': self.use_syskeyboard = False self.allow_vkeyboard = True self.single_vkeyboard = True self.docked_vkeyboard = True elif mode == 'multi': self.use_syskeyboard = False self.allow_vkeyboard = True self.single_vkeyboard = False self.docked_vkeyboard = False elif mode == 'systemanddock': self.use_syskeyboard = True self.allow_vkeyboard = True self.single_vkeyboard = True self.docked_vkeyboard = True elif mode == 'systemandmulti': self.use_syskeyboard = True self.allow_vkeyboard = True self.single_vkeyboard = False self.docked_vkeyboard = False Logger.info( 'Window: virtual keyboard %sallowed, %s, %s' % ( '' if self.allow_vkeyboard else 'not ', 'single mode' if self.single_vkeyboard else 'multiuser mode', 'docked' if self.docked_vkeyboard else 'not docked'))
def ensure_window(self): '''Ensure that we have a window. ''' import kivy.core.window # NOQA if not self.window: Logger.critical('App: Unable to get a Window, abort.') sys.exit(1)
def help_popup(key, widget, arrow_pos='bottom_mid'): ''' Display a help popup message. This message will only show once (first time help for users) Args: key: the key representing the help text widget: the widget to center on arrow_pos: help arrow position, as defined in kivy Bubble widget. ''' try: settings = HelpInfo.settings show_help = settings.userPrefs.get_pref('help', key, True) if show_help == True: helptext = HelpInfo.get_helptext(key) if helptext: content = HelpInfo( key, title_text=helptext['title'], help_text=helptext['text']) help_popup = HelpBubble(arrow_pos=arrow_pos, size=HelpInfo.HELP_POPUP_SIZE, size_hint=(None, None)) help_popup.add_widget(content) help_popup.auto_dismiss_timeout( HelpInfo.HELP_POPUP_TIMEOUT) widget.get_root_window().add_widget(help_popup) help_popup.center_on(widget) except Exception as e: Logger.critical( 'HelpInfo: Failed to show help popup: {} {}'.format(e, traceback.format_exc()))
def configure_keyboards(self): # Configure how to provide keyboards (virtual or not) # register system keyboard to listening keys from window sk = self._system_keyboard self.bind(on_key_down=sk._on_window_key_down, on_key_up=sk._on_window_key_up) # use the device's real keyboard self.use_syskeyboard = True # use the device's real keyboard self.allow_vkeyboard = False # one single vkeyboard shared between all widgets self.single_vkeyboard = True # the single vkeyboard is always sitting at the same position self.docked_vkeyboard = False # now read the configuration mode = Config.get("kivy", "keyboard_mode") if mode not in ("", "system", "dock", "multi", "systemanddock", "systemandmulti"): Logger.critical("Window: unknown keyboard mode %r" % mode) # adapt mode according to the configuration if mode == "system": self.use_syskeyboard = True self.allow_vkeyboard = False self.single_vkeyboard = True self.docked_vkeyboard = False elif mode == "dock": self.use_syskeyboard = False self.allow_vkeyboard = True self.single_vkeyboard = True self.docked_vkeyboard = True elif mode == "multi": self.use_syskeyboard = False self.allow_vkeyboard = True self.single_vkeyboard = False self.docked_vkeyboard = False elif mode == "systemanddock": self.use_syskeyboard = True self.allow_vkeyboard = True self.single_vkeyboard = True self.docked_vkeyboard = True elif mode == "systemandmulti": self.use_syskeyboard = True self.allow_vkeyboard = True self.single_vkeyboard = False self.docked_vkeyboard = False Logger.info( "Window: virtual keyboard %sallowed, %s, %s" % ( "" if self.allow_vkeyboard else "not ", "single mode" if self.single_vkeyboard else "multiuser mode", "docked" if self.docked_vkeyboard else "not docked", ) )
def ensure_window(self): """Ensure that we have an window """ import kivy.core.window if not self.window: Logger.critical("App: Unable to get a Window, abort.") sys.exit(1)
def handle_exception(self, exception_info): if type(exception_info) == KeyboardInterrupt: Logger.info("Main: KeyboardInterrupt") sys.exit() if 'sentry_client' in globals(): ident = sentry_client.captureException(value=exception_info) Logger.critical("CrashHandler: crash caught: Reference is %s" % ident) traceback.print_exc() return ExceptionManager.PASS
def start_a_new_sequence(self, message, *args): self.__init__() # ------------------------------------------------------------------------------- Read The File for coding in ['windows-1252', 'windows-1252', 'UTF-8', 'ASCII', 'ISO-8859-1']: try: seq_file = open(message[2], 'r') content = seq_file.read() seq_file.close() self.base_seq_dir = os.path.dirname(message[2]) Logger.info("start_a_new_sequence: base folder: {}".format(self.base_seq_dir)) Logger.info("start_a_new_sequence: {} well decoded in {}".format(message[2], coding)) #Logger.info("start_a_new_sequence: Testo:\n{}".format(content)) break except UnicodeDecodeError: Logger.critical( "start_a_new_sequence: {} Tentata codifica {} errata".format(message[2], coding)) pass # ------------------------------------------------------------------------------- First Parsing: find separator max_count = 0 for s in self.separators: occurrences = content.count(s) if occurrences > max_count: self.official_separator = s max_count = occurrences parameter = True page_rst = "{}\n===========\n{}".format(self.title, content) page_line_count = 0 for s in content.replace('\r', '').split('\n'): # ----------------------------------------------------------------------------- Parsing High part, Title, etc. if parameter: val = s.split(self.official_separator) if val[0].find("Start of the sequence") > -1: # Inizio Sequenza ____________________________ parameter = False else: # is a valid parameter _______________________________ try: setattr(self, val[0], val[1]) # ToDo in python 3 remove! page_rst = "{}\n===========\n\nSelf Generated sequence:\n\n".format(self.title) except UnicodeEncodeError: setattr(self, 'title', val[1]) # ToDo in python 3 remove! Logger.debug('start_a_new_sequence: Tarokked the title: {}'.format(val[1])) # ----------------------------------------------------------------------------- Parsing Excercises else: # Decoding istructions from here _______________________________________________ if s.count(self.official_separator) >= 2: # It is a valid instruction, at least 3 operand self.new_activity(["", "", s]) # ToDo Valutation about this mess page_line_count += 1 page_rst += "{:02d}. {}\n\n".format(page_line_count, s) self._initialize_image(0) rst_file = os.path.join(self.base_seq_dir, 'info.rst') if not os.path.exists(rst_file): page_file = open(rst_file, 'w') page_file.write(page_rst) page_file.close() self.push_message([rst_file], '/sld') Logger.info("New Sequence Loaded: Title: {} ({} seconds, {} elements)".format( self.title, format_seconds(self.time_duration), len(self.seq_timings))) tts.speak("Sequence Loaded")
def core_select_lib(category, llist, create_instance=False, base='kivy.core'): if 'KIVY_DOC' in os.environ: return category = category.lower() libs_ignored = [] 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( category, 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: libs_ignored.append(modulename) Logger.debug('{0}: Ignored <{1}> (import error)'.format( category.capitalize(), option)) Logger.trace('', exc_info=e) except CoreCriticalException as e: 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: libs_ignored.append(modulename) Logger.trace('{0}: Unable to use {1}'.format( category.capitalize(), option, category)) Logger.trace('', exc_info=e) Logger.critical( '{0}: Unable to find any valuable {1} provider at all!'.format( category.capitalize(), category.capitalize()))
def get_cover(self): data_folder = App.get_running_app().config.get('Server', 'storagedir') cover_file = '%s/%s.png'%(data_folder,str(self.comic_id_number)) try: if os.path.isfile(cover_file): return str(cover_file) else: proxyImage = Loader.image(self.thumb_url,nocache=True) proxyImage.bind(on_load=partial(self._proxy_loaded)) return self.thumb_url except: Logger.critical('Something bad happened in loading cover')
def ZipSingleFile(uFile, uZipDest,uRemovePath=''): ''' Zips a single file ''' try: oZipFile = ZipFile(uZipDest, 'w',ZIP_DEFLATED) if uRemovePath=='': oZipFile.write(uFile) else: uArc=uFile[len(uRemovePath):] oZipFile.write(uFile,uArc) oZipFile.close() except Exception as e: uMsg=u'Zip: Fatal Error Zipping File:'+ToUnicode(e) Logger.critical (uMsg) return False
def __init__(self, **kwargs): # XXX move to style.kv kwargs.setdefault('size_hint', (None, None)) kwargs.setdefault('scale_min', .4) kwargs.setdefault('scale_max', 1.6) kwargs.setdefault('size', (700, 200)) kwargs.setdefault('docked', False) self._trigger_update_layout_mode = Clock.create_trigger( self._update_layout_mode) self._trigger_load_layouts = Clock.create_trigger( self._load_layouts) self._trigger_load_layout = Clock.create_trigger( self._load_layout) self.bind( docked=self.setup_mode, have_shift=self._trigger_update_layout_mode, have_capslock=self._trigger_update_layout_mode, layout_path=self._trigger_load_layouts, layout=self._trigger_load_layout) self.register_event_type('on_key_down') self.register_event_type('on_key_up') super(VKeyboard, self).__init__(**kwargs) # load all the layouts found in the layout_path directory self._load_layouts() # ensure we have default layouts available_layouts = self.available_layouts if not available_layouts: Logger.critical('VKeyboard: unable to load default layouts') # load the default layout from configuration if self.layout is None: self.layout = Config.get('kivy', 'keyboard_layout') else: # ensure the current layout is found on the available layout self._trigger_load_layout() # update layout mode (shift or normal) self._trigger_update_layout_mode() # create a top layer to draw active keys on with self.canvas: self.background_key_layer = Canvas() self.active_keys_layer = Canvas() # prepare layout widget self.refresh_keys_hint() self.refresh_keys()
def add_update_comic(cls): try: with database.atomic(): new_comic = Comics.create( comicstream_number=cls.comicstream_number, added_ts=cls.added_ts, comments=cls.comments, date=cls.pubdate, issue=cls.issue, page_count=cls.page_count, publisher=cls.publisher, series=cls.series, title=cls.title, volume=cls.volume, mod_ts = cls.mod_ts, month = cls.month, year=cls.year, weblink=cls.weblink, page_cout=cls.page_count # teams=cls.teams, ) if not cls.storyarcs == None: add_story_arcs(new_comic.comicstream_number, cls.storyarcs) Logger.debug('started story %s' %cls.storyarcs) except ValueError: Logger.critical('ValuError doing %s and month %s' % (cls.comicstream_number , cls.month)) except IntegrityError: new_comic = Comics.get(Comics.comicstream_number == cls.comicstream_number) new_comic.added_ts=cls.added_ts new_comic.comments=cls.comments new_comic.date=cls.pubdate new_comic.issue=cls.issue new_comic.page_count=cls.page_count new_comic.publisher=cls.publisher new_comic.series=cls.series new_comic.title=cls.title new_comic.volume=cls.volume new_comic.mod_ts = cls.mod_ts new_comic.month = cls.month new_comic.year=cls.year new_comic.weblink=cls.weblink new_comic.page_count=cls.page_count #new_comic.teams=cls.teams new_comic.save() if not cls.storyarcs == None: add_story_arcs(new_comic.comicstream_number, cls.storyarcs) Logger.debug('started story %s' %cls.storyarcs)
def probe(self): global EventLoop from kivy.base import EventLoop inputs = get_inputs(self.input_path) Logger.debug('ProbeSysfs: using probesysfs!') use_mouse = self.should_use_mouse() if not self.select_all: inputs = [x for x in inputs if x.has_capability(ABS_MT_POSITION_X) and (use_mouse or not x.is_mouse)] for device in inputs: Logger.debug('ProbeSysfs: found device: %s at %s' % ( device.name, device.device)) # must ignore ? if self.match: if self.use_regex: if not match(self.match, device.name, IGNORECASE): Logger.debug('ProbeSysfs: device not match the' ' rule in config, ignoring.') continue else: if self.match not in device.name: continue Logger.info('ProbeSysfs: device match: %s' % device.device) d = device.device devicename = self.device % dict(name=d.split(sep)[-1]) provider = MotionEventFactory.get(self.provider) if provider is None: Logger.info('ProbeSysfs: unable to found provider %s' % self.provider) Logger.info('ProbeSysfs: fallback on hidinput') provider = MotionEventFactory.get('hidinput') if provider is None: Logger.critical('ProbeSysfs: no input provider found' ' to handle this device !') continue instance = provider(devicename, '%s,%s' % ( device.device, ','.join(self.args))) if instance: EventLoop.add_input_provider(instance)
def open_mag_glass(self): Logger.debug('my id=%s' % str(self.id)) mag_glass_setting_x = int(App.get_running_app().config.get('Display', 'mag_glass_size')) mag_glass_setting_y = int(App.get_running_app().config.get('Display', 'mag_glass_size')) comic_image_id = self.id.replace('comic_scatter','pi_') print App.get_running_app().root.ids try: for child in self.walk(): print child.id if child.id == comic_image_id: image_w = child Logger.debug('>>>>>Found grandchild named %s this is the image' %comic_image_id) elif child.id == 'mag_glass': mag_glass_w = child except: Logger.critical('Some bad happened in _call_mag') else: print 'image_w = %s' % str(image_w) if self.move_state == 'open': self.move_state = 'locked' self.do_scale=False self.do_translation=False Logger.debug('image_w.center = %d,%d' % (image_w.center_x,image_w.center_y)) mag_glass = MagnifyingGlassScatter(size=(mag_glass_setting_x,mag_glass_setting_y),size_hint = (None, None), do_rotation=False, do_scale=False, pos=((image_w.center_x-(mag_glass_setting_x/2)), (image_w.center_y-(mag_glass_setting_y/2)) ),id='mag_glass' ) mag_glass.page_widget = image_w mag_glass_image = Image(size_hint= (None,None),pos_hint={'x':1, 'y':1},id='mag_image',keep_ratio=True, allow_stretch=False,size=mag_glass.size ) mag_glass.mag_img = mag_glass_image mag_glass_image.texture = image_w.texture.get_region( mag_glass.x,mag_glass.y,mag_glass_setting_x,mag_glass_setting_y) mag_glass.add_widget(mag_glass_image) self.add_widget(mag_glass) else: self.move_state = 'open' self.do_scale=True self.do_translation=True self.remove_widget(mag_glass_w)
def _get_cs_thumb(self): src = "%s/comic/%d/thumbnail" % (self.base_url, int(self.comicstream_number)) comic_dir = '%s/%s' %(self.base_dir, self.comicstream_number) if not os.path.exists(comic_dir): os.makedirs(comic_dir) fname='%s/%d_thumb.jpg' %(comic_dir, self.comicstream_number) if not os.path.isfile(fname): try: r = requests.get(src) r.raise_for_status() except HTTPError: Logger.critical('HTTPerror for %s' % src ) else: with open(fname,'w') as f: f.write(r.content) Logger.debug('file is %s' % fname) return fname
def core_select_lib(category, llist, create_instance=False): if "KIVY_DOC" in os.environ: return category = category.lower() for option, modulename, classname in llist: try: # module activated in config ? if option not in kivy.kivy_options[category]: Logger.debug("%s: option <%s> ignored by config" % (category.capitalize(), option)) continue # import module mod = __import__( name="%s.%s" % (category, modulename), globals=globals(), locals=locals(), fromlist=[modulename], level=-1, ) cls = mod.__getattribute__(classname) # ok ! Logger.info("%s: using <%s> as %s provider" % (category.capitalize(), option, category)) if create_instance: cls = cls() return cls except ImportError as e: Logger.warning("%s: Unable to use <%s> as %s" "provider" % (category.capitalize(), option, category)) Logger.warning("%s: Associated module are missing" % (category.capitalize())) Logger.debug("", exc_info=e) except CoreCriticalException as e: Logger.error("%s: Unable to use <%s> as %s" "provider" % (category.capitalize(), option, category)) Logger.error("%s: The module raised an important error: %r" % (category.capitalize(), e.message)) raise except Exception as e: Logger.warning("%s: Unable to use <%s> as %s" "provider" % (category.capitalize(), option, category)) Logger.debug("", exc_info=e) Logger.critical( "%s: Unable to find any valuable %s provider " "at all!" % (category.capitalize(), category.capitalize()) )
def start_a_new_sequence(self, message, *args): self.__init__() max_count = 0 for coding in ['windows-1252', 'windows-1252', 'UTF-8', 'ASCII', 'ISO-8859-1']: try: seq_file = open(message[2], 'r') content = seq_file.read() seq_file.close() self.base_seq_dir = os.path.dirname(message[2]) Logger.info("start_a_new_sequence: base folder: {}".format(self.base_seq_dir)) Logger.info("start_a_new_sequence: {} well decoded in {}".format(message[2], coding)) Logger.info("start_a_new_sequence: Testo:\n{}".format(content)) break except UnicodeDecodeError: Logger.critical( "start_a_new_sequence: {} Tentata codifica {} errata".format(message[2], coding)) pass for s in self.separators: occurrences = content.count(s) if occurrences > max_count: self.official_separator = s max_count = occurrences parameter = True #setattr(self, 'title', 'now works') for s in content.replace('\r', '').split('\n'): if parameter: val = s.split(self.official_separator) print val[0], val[1] if val[0].find("Start of the sequence") > -1: # Inizio Sequenza ____________________________ parameter = False else: # is a valid parameter _______________________________ try: setattr(self, val[0], val[1]) # ToDo in python 3 remove! except UnicodeEncodeError: setattr(self, 'title', val[1]) # ToDo in python 3 remove! Logger.debug('start_a_new_sequence: Tarokked the title: {}'.format(val[1])) else: # Decoding istructions from here _______________________________________________ if s.count(self.official_separator) > 1: # It is a valid instruction, at least 3 operand self.new_activity(["", "", s]) # ToDo Valutation about this mess self._initialize_image(0) Logger.info("New Sequence Loaded: Title: {} ({} seconds, {} elements)".format( self.title, format_seconds(self.time_duration), len(self.seq_timings))) tts.speak("Sequence Loaded: {}".format(self.title))
def _process_events_before_frame(self): found = True count = self.max_iteration events = self._events while found: count -= 1 if count == -1: Logger.critical('Clock: Warning, too much iteration done before' ' the next frame. Check your code, or increase' ' the Clock.max_iteration attribute') break # search event that have timeout = -1 found = False for cid in events.keys()[:]: for event in events[cid][:]: if event.timeout != -1: continue found = True if event.tick(self._last_tick) is False: # event may be already removed by the callback if event in events[cid]: events[cid].remove(event)
def print_gl_version(): version = glGetString(GL_VERSION) vendor = glGetString(GL_VENDOR) renderer = glGetString(GL_RENDERER) Logger.info('GL: OpenGL version <{0}>'.format(version)) Logger.info('GL: OpenGL vendor <{0}>'.format(vendor)) Logger.info('GL: OpenGL renderer <{0}>'.format(renderer)) # Let the user know if his graphics hardware/drivers are too old major, minor = gl_get_version() Logger.info('GL: OpenGL parsed version: %d, %d' % (major, minor)) if (major, minor) < MIN_REQUIRED_GL_VERSION and not \ bool(int(environ.get('USE_OPENGL_MOCK', 0))): if hasattr(sys, "_kivy_opengl_required_func"): sys._kivy_opengl_required_func(major, minor, version, vendor, renderer) else: msg = ( 'GL: Minimum required OpenGL version (2.0) NOT found!\n\n' 'OpenGL version detected: {0}.{1}\n\n' 'Version: {2}\nVendor: {3}\nRenderer: {4}\n\n' 'Try upgrading your graphics drivers and/or your ' 'graphics hardware in case of problems.\n\n' 'The application will leave now.').format( major, minor, version, vendor, renderer) Logger.critical(msg) msgbox(msg) if platform != 'android': # XXX in the android emulator (latest version at 22 march 2013), # this call was segfaulting the gl stack. Logger.info('GL: Shading version <{0}>'.format( glGetString(GL_SHADING_LANGUAGE_VERSION))) Logger.info('GL: Texture max size <{0}>'.format( glGetIntegerv(GL_MAX_TEXTURE_SIZE)[0])) Logger.info('GL: Texture max units <{0}>'.format( glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS)[0]))
def __init__(self, dummy=False, *args, **kwargs): Logger.info('VolumeHandler: Loading volume-module') Logger.name = 'VolumeHandler' # Dummy mode? self.dummy = dummy if self.dummy: self.MIXER_NAME = 'Master' # Find sound card try: self.cardIndex = alsaaudio.cards().index(self.CARD_NAME) except ValueError: Logger.warning( 'Sound card "{}" has not been found! Selected default card.'. format(self.CARD_NAME)) # Find mixer try: self.mixer = alsaaudio.Mixer(self.MIXER_NAME, cardindex=self.cardIndex) except alsaaudio.ALSAAudioError: Logger.critical( 'Could not find mixer "{}" on card "{}"! Aborting.'.format( self.MIXER_NAME, self.cardIndex)) sys.exit(1) # Set initial values self.isMuted = bool(self.mixer.getmute( )[0]) # We only get one channel but the two should be in sync anyway self.current = int(self.mixer.getvolume()[0]) # Register events self.register_event_type('on_volume_change') self.register_event_type('on_mute_change') super(VolumeHandler, self).__init__(*args, **kwargs)
def TarFile(self,*, oTarDest:cFileName, uRemovePath:str='', uCompressionMode:str = "") -> bool: """ tars a single file to a tar file :param oTarDest: Destination tar file :param uRemovePath: Removes a specific folder part from the the tar file :param uCompressionMode: Sets Compression Mode: If not given, it will be taken from the file extension :return: True is successful """ uMode:str try: uMode = GetWriteMode(oFnTarDest=oTarDest,uDefaultMode=uCompressionMode) oTarFile:tarfile.TarFile = tarfile.open(name=oTarDest.string, mode=uMode) if uRemovePath == '': oTarFile.add(name=self.string) else: uArc:str = self.string[len(uRemovePath):] oTarFile.add(name=self.string, arcname=uArc) oTarFile.close() return True except Exception as e: Logger.critical(u'Tar: Fatal Error Taring File:' + ToUnicode(e)) return False
def _start_app_as_slave(self): # from app::run if not self.mc.built: self.mc.load_config() self.mc.load_kv(filename=self.mc.kv_file) root = self.mc.build() if root: self.mc.root = root if self.mc.root: if not isinstance(self.mc.root, KivyWidget): Logger.critical( 'App.root must be an _instance_ of Kivy Widget') raise Exception('Invalid instance in App.root') from kivy.core.window import Window Window.add_widget(self.mc.root) # Check if the window is already created from kivy.base import EventLoop window = EventLoop.window if window: self.mc._app_window = window window.set_title(self.mc.get_application_name()) icon = self.mc.get_application_icon() if icon: window.set_icon(icon) self.mc._install_settings_keys(window) else: Logger.critical("Application: No window is created." " Terminating application run.") return self.mc.dispatch('on_start') runTouchApp(embedded=True) # change is here while not self.mc.is_init_done.is_set(): EventLoop.idle()
def _process_events_before_frame(self): found = True count = self.max_iteration events = self._events while found: count -= 1 if count == -1: Logger.critical( 'Clock: Warning, too much iteration done before' ' the next frame. Check your code, or increase' ' the Clock.max_iteration attribute') break # search event that have timeout = -1 found = False for events in self._events: remove = events.remove for event in events[:]: if event.timeout != -1: continue found = True # event may be already removed from original list if event in events: event.tick(self._last_tick, remove)
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
def my_key_handler(self, window, key, *args): if key == 27: Logger.critical('Pressed Back Button!') if self.sm.current in ['settings', 'rules', 'about']: self.sm.current = 'startmenu' else: Logger.critical('Check if it\'s android') if platform == 'android': Logger.critical('platform is Android') PythonActivity = jnius.autoclass( 'org.renpy.android.PythonActivity') Intent = jnius.autoclass('android.content.Intent') intent = Intent(Intent.ACTION_MAIN) intent.addCategory(Intent.CATEGORY_HOME) intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) currentActivity = jnius.cast('android.app.Activity', PythonActivity.mActivity) currentActivity.startActivity(intent) return True return True return False
def create(outname, filenames, size, padding=2, use_path=False): '''This method can be used to create an atlas manually from a set of images. :Parameters: `outname`: str Basename to use for ``.atlas`` creation and ``-<idx>.png`` associated images. `filenames`: list List of filenames to put in the atlas. `size`: int or list (width, height) Size of the atlas image. `padding`: int, defaults to 2 Padding to put around each image. Be careful. If you're using a padding < 2, you might have issues with the borders of the images. Because of the OpenGL linearization, it might use the pixels of the adjacent image. If you're using a padding >= 2, we'll automatically generate a "border" of 1px around your image. If you look at the result, don't be scared if the image inside is not exactly the same as yours :). `use_path`: bool, defaults to False If True, the relative path of the source png file names will be included in the atlas ids rather that just in the file names. Leading dots and slashes will be excluded and all other slashes in the path will be replaced with underscores. For example, if `use_path` is False (the default) and the file name is ``../data/tiles/green_grass.png``, the id will be ``green_grass``. If `use_path` is True, it will be ``data_tiles_green_grass``. .. 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 if isinstance(size, (tuple, list)): size_w, size_h = map(int, size) else: size_w = size_h = int(size) # open all of the images ims = list() for f in filenames: fp = open(f) im = Image.open(fp) im.load() fp.close() ims.append((f, im)) # 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_w, size_h)] 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_w or imh > size_h: Logger.error( 'Atlas: image %s (%d by %d) is larger than the atlas size!' % (imageinfo[0], imw, imh)) 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_w, size_h)) 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{1} rgba image'.format( size_w, size_h)) outimages = [ Image.new('RGBA', (size_w, size_h)) 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_h - y - h, w, h outfn = '%s.atlas' % outname with open(outfn, 'w') as fd: json.dump(meta, fd) return outfn, meta
text_size = property(_get_text_size, _set_text_size, doc='''Get/set the (width, height) of the ' 'contrained rendering box''') usersize = property(_get_text_size, _set_text_size, doc='''(deprecated) Use text_size instead.''') # Load the appropriate provider Label = core_select_lib('text', ( ('pygame', 'text_pygame', 'LabelPygame'), ('sdl2', 'text_sdl2', 'LabelSDL2'), ('sdlttf', 'text_sdlttf', 'LabelSDLttf'), ('pil', 'text_pil', 'LabelPIL'), )) if 'KIVY_DOC' not in os.environ: if not Label: from kivy.logger import Logger import sys Logger.critical('App: Unable to get a Text provider, abort.') sys.exit(1) # For the first initalization, register the default font Label.register('DroidSans', 'data/fonts/DroidSans.ttf', 'data/fonts/DroidSans-Italic.ttf', 'data/fonts/DroidSans-Bold.ttf', 'data/fonts/DroidSans-BoldItalic.ttf')
def got_redirect(self, req, results): Logger.critical("----got_redirect--") Logger.critical("ERROR in %s %s" % (inspect.stack()[0][3], results))
LD_LIBRARY_PATH = CEF_DIR else: LD_LIBRARY_PATH += os.pathsep + CEF_DIR os.putenv('LD_LIBRARY_PATH', LD_LIBRARY_PATH) elif PLATFORM == 'win': # Add the DLL and export the PATH for windows SUBPROCESS += ".exe" libcef = os.path.join(CEF_DIR, "libcef.dll") PATH = os.environ.get('PATH', None) if not PATH: PATH = CEF_DIR else: PATH += os.pathsep + CEF_DIR os.putenv('PATH', PATH) else: Logger.critical("CEFLoader: Unsupported platform: %s", PLATFORM) raise Exception("Unsupported platform") sys.path += [CEF_DIR] # Load precompiled cefpython from source if not os.path.exists(libcef) and LIB_ID in SOURCES: s = SOURCES[LIB_ID] Logger.debug("CEFLoader: SOURCE: %s", json.dumps(s, indent=4)) Logger.info("CEFLoader: Loading precompiled cefpython for " + LIB_ID + "...") path = CEF_DIR + ".dat" if os.path.exists(path): os.unlink(path) if not os.path.exists(CEF_DIR): os.makedirs(CEF_DIR) Logger.debug("CEFLoader: Downloading from " + s["url"] + " ...")
def on_stop(self): Logger.critical('Remember me ')
self._rc_api.shutdown_api() self.init_rc_comms() def _on_session_recording(self, instance, is_recording): toast('Session recording started' if is_recording else 'Session recording stopped', 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
the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import traceback from kivy.logger import Logger from ORCA.App import ORCA_App ORCA = None try: ORCA = ORCA_App() if __name__ in ('__android__', '__main__'): ORCA.run() except Exception as exception: uMsg = 'ORCA:Unexpected error:' + str(exception) Logger.critical(uMsg) uMsg = traceback.format_exc() Logger.critical(uMsg) if ORCA is not None: ORCA.StopApp() pass
#Config.set('kivy','window_icon', BASEPATH+'includes/icons/DaytimeLog.png') self.icon = 'includes/icons/DaytimeLog.png' #keyboard #Window.keyboard_on_key_down= def TaskInit(self): #in suppose that you use the app today and still open it tommorrow Window.bind(on_cursor_enter=self.RefreshContent) #when request close Window.bind(on_request_close=self.screenManager.OnLeaving) #listen to shortcut #self.screenManager.RequestKeyboard() #AutoSave def RefreshContent(self, *args): self.todayView.Refresh() def build(self): self.SysInit() self.ViewInit() self.TaskInit() #self.screenManager.current='reportView' return self.screenManager if __name__ == '__main__': try: DaytimeLogApp().run() except: Logger.critical('crashed', exc_info=True, stack_info=True)
def critical(self, msg, *args, **kwargs): msg = '%s: %s' % (self.name, msg) Logger.critical(msg, *args, **kwargs)
from os import environ, mkdir from os.path import dirname, join, basename, exists, expanduser from kivy.logger import Logger, LOG_LEVELS from kivy.utils import platform # internals for post-configuration __kivy_post_configuration = [] if platform() == 'macosx' and sys.maxint < 9223372036854775807: r = '''Unsupported Python version detected!: Kivy requires a 64 bit version of Python to run on OS X. We strongly advise you to use the version of Python that is provided by Apple (don't use ports, fink or homebrew unless you know what you're doing). See http://kivy.org/docs/installation/installation-macosx.html for details. ''' Logger.critical(r) def require(version): '''Require can be used to check the minimum version required to run a Kivy application. For example, you can start your application code like this:: import kivy kivy.require('1.0.1') If a user attempts to run your application with a version of Kivy that is older than the specified version, an Exception is raised. The Kivy version string is built like this:: X.Y.Z[-tag[-tagrevision]]
import tempfile import kivy from kivy.app import App from kivy.clock import Clock from kivy.logger import Logger kivy.require("1.8.0") # Try import from package (PYTHONPATH) try: from cefpython3 import cefpython Logger.info("CEFLoader: cefpython3 imported from package") except ImportError: Logger.critical("CEFLoader: Failed to import cefpython") raise Exception("Failed to import cefpython") cefpython_loop_event = None def cefpython_initialize(cef_browser_cls): global cefpython_loop_event if cefpython_loop_event: Logger.warning( "CEFLoader: Attempt to initialize CEFPython another time") return try: md = cefpython.GetModuleDirectory() except Exception as e: raise Exception("CEFLoader: Could not define module-directory: %s" % e)
def Init(self): """ first real init step Sets some basic vars and find/sets the path to the orca files """ try: ''' oPathAppReal: The path where the OS Installer places the installation files, eg the the fallback action files Could be every where and could be a read only location Not necessary the place where the binaries are oPathRoot: This is the path, where to find the (downloaded) ORCA files. Can be changed in the settings ''' Globals.oPathAppReal = OS_GetInstallationDataPath() Globals.oPathRoot = OS_GetUserDataPath() Globals.uIPAddressV4, Globals.uIPGateWayAssumedV4, Globals.uIPSubNetAssumedV4 = GetLocalIPV4( ) Globals.uIPAddressV6, Globals.uIPGateWayAssumedV6 = GetLocalIPV6() Globals.uMACAddressColon, Globals.uMACAddressDash = GetMACAddress() if Globals.oParameter.oPathDebug.string: Globals.oPathRoot = Globals.oParameter.oPathDebug Logger.info('OrcaAppInit (Root/Real): Path: ' + Globals.oPathAppReal) Logger.info('OrcaAppInit (Root) : Path: ' + Globals.oPathRoot) SetVar(uVarName=u'APPLICATIONPATH', oVarValue=Globals.oPathRoot.string) SetVar(uVarName=u'WIZARDTEMPLATESPATH', oVarValue=(Globals.oPathRoot + "wizard templates").unixstring) if not Globals.oPathRoot.IsDir(): Globals.oPathRoot.Create() # Read all custom settings if not self.InitAndReadSettingsPanel(): return False Globals.oLanguage.Init() # Init the Languages (dont load them) Globals.oInterFaces.LoadInterfaceList( ) # load the list of all available interfaces Globals.oScripts.LoadScriptList( ) # load the list of all available scripts # Create the atlas files for the skin and the definition if Globals.oDefinitionPathes.oPathDefinition.Exists(): if Globals.uDefinitionName != "setup": CreateAtlas(Globals.oDefinitionPathes.oPathDefinition, Globals.oDefinitionPathes.oFnDefinitionAtlas, u'Create Definition Atlas Files') Globals.bInit = True return True except Exception as e: uMsg = LogError(u'App Init:Unexpected error:', e) Logger.critical(uMsg) ShowErrorPopUp(uTitle='Fatal Error', uMessage=uMsg, bAbort=True, uTextContinue='', uTextQuit=u'Quit') self.bOnError = True return 0
def create(outname, filenames, size, padding=2): '''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 :). ''' # 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 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
def InitAndReadSettingsPanel(self): """ Reads the complete settings from the orca.ini file it will set setting defaults, if we do not have an ini file by now """ try: ''' if Globals.oParameter.oPathLog is not None: oPathLogfile = Globals.oParameter.oPathLog else: oPathLogfile = cPath(Globals.oPathRoot) + "logs" oPathLogfile.Create() kivyConfig.set('kivy', 'log_dir', oPathLogfile.string) kivyConfig.write() uOrgLogFn=Logger.manager.loggerDict["kivy"].handlers[1].filename Logger.debug(u"Init: Original Startup Logile at :"+uOrgLogFn) ''' Logger.level = Logger.level Globals.fDoubleTapTime = ToFloat( kivyConfig.getint('postproc', 'double_tap_time')) / 1000.0 self.oFnConfig = cFileName(Globals.oPathRoot) + u'orca.ini' oConfig = Globals.oOrcaConfigParser oConfig.filename = self.oFnConfig.string if self.oFnConfig.Exists(): oConfig.read(self.oFnConfig.string) if not oConfig.has_section(u'ORCA'): oConfig.add_section(u'ORCA') Globals.uDefinitionName = Config_GetDefault_Str( oConfig, u'ORCA', u'definition', u'setup') if "[" in Globals.uDefinitionName: Globals.uDefinitionName = Globals.uDefinitionName[ Globals.uDefinitionName.find("[") + 1:Globals.uDefinitionName.find("]")] if Globals.uDefinitionName == u'setup': Logger.setLevel(logging.DEBUG) oRootPath = Config_GetDefault_Path(oConfig, u'ORCA', u'rootpath', Globals.oPathRoot.string) if oRootPath.string: Globals.oPathRoot = oRootPath oFnCheck = cFileName(Globals.oPathRoot + 'actions') + 'actionsfallback.xml' if not oFnCheck.Exists(): Globals.oPathRoot = OS_GetUserDataPath() Logger.debug(u'Init: Override Path:' + Globals.oPathRoot) self.InitRootDirs() Globals.iLastInstalledVersion = Config_GetDefault_Int( oConfig, u'ORCA', 'lastinstalledversion', ToIntVersion(Globals.uVersion)) Globals.bProtected = (Globals.oPathRoot + u'protected').Exists() if Globals.bProtected: SetVar(uVarName="PROTECTED", oVarValue="1") else: SetVar(uVarName="PROTECTED", oVarValue="0") # get the installed interfaces , etc i = 0 while True: oInstalledRep = cInstalledReps() uKey = u'installedrep%i_type' % i oInstalledRep.uType = Config_GetDefault_Str( oConfig, u'ORCA', uKey, '') uKey = u'installedrep%i_name' % i oInstalledRep.uName = Config_GetDefault_Str( oConfig, u'ORCA', uKey, '') uKey = u'installedrep%i_version' % i oInstalledRep.iVersion = Config_GetDefault_Int( oConfig, u'ORCA', uKey, 0) if not oInstalledRep.uName == '': uKey = '%s:%s' % (oInstalledRep.uType, oInstalledRep.uName) Globals.dInstalledReps[uKey] = oInstalledRep i += 1 else: break del Globals.aRepositories[:] # get the configured repos for i in range(Globals.iCntRepositories): if i == 0: uDefault = 'https://www.orca-remote.org/repositories/ORCA_$var(REPVERSION)/repositories' else: uDefault = '' uKey = u'repository' + str(i) uRep = ReplaceVars( Config_GetDefault_Str(oConfig, u'ORCA', uKey, uDefault)) Globals.aRepositories.append(uRep) # we add some values for state, which helps for the Download Settings uKey = u'repository_state' + str(i) Config_GetDefault_Str(oConfig, u'ORCA', uKey, '1') # Getting the lists for skins, definitions and languages Globals.aSkinList = self.oPathSkinRoot.GetFolderList() Globals.aLanguageList = Globals.oPathLanguageRoot.GetFolderList() Globals.aDefinitionList = Globals.oPathDefinitionRoot.GetFolderList( ) Globals.uSkinName = Config_GetDefault_Str(oConfig, u'ORCA', u'skin', u'ORCA_silver_hires') self.uSoundsName = Config_GetDefault_Str(oConfig, u'ORCA', u'sounds', u'ORCA_default') Globals.uLanguage = Config_GetDefault_Str(oConfig, u'ORCA', u'language', OS_GetLocale()) Globals.uDefinitionContext = Globals.uDefinitionName if Globals.uDefinitionName == 'setup': Logger.setLevel(logging.DEBUG) if not Globals.uLanguage in Globals.aLanguageList: if len(Globals.aLanguageList) > 0: Globals.uLanguage = Globals.aLanguageList[0] oConfig.set(u'ORCA', u'language', Globals.uLanguage) Globals.uLocalesName = Config_GetDefault_Str( oConfig, u'ORCA', u'locales', u'UK (12h)') if 'shared_documents' in Globals.aDefinitionList: Globals.aDefinitionList.remove('shared_documents') if not Globals.uDefinitionName in Globals.aDefinitionList: if len(Globals.aDefinitionList) > 0: Globals.uDefinitionName = Globals.aDefinitionList[0] oConfig.set(u'ORCA', u'definition', Globals.uDefinitionName) if not Globals.uSkinName in Globals.aSkinList: if len(Globals.aSkinList) > 0: Globals.uSkinName = Globals.aSkinList[0] oConfig.set(u'ORCA', u'skin', Globals.uSkinName) oConfig.set(u'ORCA', u'interface', ReplaceVars("select")) oConfig.set(u'ORCA', u'script', ReplaceVars("select")) oConfig.set(u'ORCA', u'definitionmanage', ReplaceVars("select")) Globals.bInitPagesAtStart = Config_GetDefault_Bool( oConfig, u'ORCA', u'initpagesatstartup', u'0') Globals.fDelayedPageInitInterval = Config_GetDefault_Float( oConfig, u'ORCA', u'delayedpageinitinterval', u'60') Globals.fStartRepeatDelay = Config_GetDefault_Float( oConfig, u'ORCA', u'startrepeatdelay', u'0.8') Globals.fContRepeatDelay = Config_GetDefault_Float( oConfig, u'ORCA', u'contrepeatdelay', u'0.2') Globals.fLongPressTime = Config_GetDefault_Float( oConfig, u'ORCA', u'longpresstime', u'1') Globals.bConfigCheckForNetwork = Config_GetDefault_Bool( oConfig, u'ORCA', u'checkfornetwork', u'1') Globals.uNetworkCheckType = Config_GetDefault_Str( oConfig, u'ORCA', u'checknetworktype', OS_GetDefaultNetworkCheckMode()) Globals.uConfigCheckNetWorkAddress = Config_GetDefault_Str( oConfig, u'ORCA', u'checknetworkaddress', 'auto') Globals.bClockWithSeconds = Config_GetDefault_Bool( oConfig, u'ORCA', u'clockwithseconds', u'1') Globals.bLongDate = Config_GetDefault_Bool(oConfig, u'ORCA', u'longdate', u'0') Globals.bLongDay = Config_GetDefault_Bool(oConfig, u'ORCA', u'longday', u'0') Globals.bLongMonth = Config_GetDefault_Bool( oConfig, u'ORCA', u'longmonth', u'0') Globals.bVibrate = Config_GetDefault_Bool(oConfig, u'ORCA', u'vibrate', u'0') Globals.bIgnoreAtlas = Config_GetDefault_Bool( oConfig, u'ORCA', u'ignoreatlas', u'0') Globals.fScreenSize = Config_GetDefault_Float( oConfig, u'ORCA', u'screensize', u'0') if Globals.fScreenSize == 0: Globals.fScreenSize = math.sqrt( Globals.iAppWidth**2 + Globals.iAppHeight**2) / Metrics.dpi self.InitOrientationVars() Globals.uStretchMode = Config_GetDefault_Str( oConfig, u'ORCA', u'stretchmode', OS_GetDefaultStretchMode()) Globals.oSound.ReadSoundVolumesFromConfig(oConfig) oConfig.write() self.InitPathes() # init all used pathes # clear cache in case of an update if self.bClearCaches: ClearAtlas() # Create and read the definition ini file Globals.oDefinitionConfigParser = oConfig = OrcaConfigParser() oConfig.filename = Globals.oDefinitionPathes.oFnDefinitionIni.string if Globals.oDefinitionPathes.oFnDefinitionIni.Exists(): oConfig.read(Globals.oDefinitionPathes.oFnDefinitionIni.string) uSection = Globals.uDefinitionName uSection = uSection.replace(u' ', u'_') if not oConfig.has_section(uSection): oConfig.add_section(uSection) return True except Exception as e: uMsg = u'Global Init:Unexpected error reading settings:' + ToUnicode( e) Logger.critical(uMsg) ShowErrorPopUp(uTitle='Fatal Error', uMessage=uMsg, bAbort=True, uTextContinue='', uTextQuit=u'Quit') return 0
def got_failure(self, req, results): Logger.critical("----got_failure--") Logger.critical("ERROR in %s %s" % (inspect.stack()[0][3], results))
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))
def _Next_Play(): Logger.info('---------- _Next_Play fired for player ' + str(cPlayer) + ' ---------------, chicago gameState = ' + str(gsInst.gameState['chicago'])) Logger.info('controlPlayer = ' + str(gsInst.gameState['controlPlayer'])) if gsInst.hand[cPlayer]['cpu'] is False: return self.Human_Next_Turn(gsInst) ##Showdown CPU Play def Play_Card(scatterID): Logger.info('Play_Card fired with : ' + str(scatterID)) duration = 1.2 if Configed_Bool("General", "fastPlay") is True: duration = 0.5 def smallcardGone(a, w): def setTmpActiveCard(a, w): cID = self.ID_Card( gsInst.hand[cPlayer]['cardid'][scatterID]) gsInst.gameState['tmpActiveCard'] = (scatterID, cID[0], cID[1]) Logger.info('ending from setTmpActiveCard') gsInst.End_Turn() #turn card face up card = gsInst.ids['card' + str(scatterID)] cImage = gsInst.ids['card' + str(scatterID) + 'Image'] cImage.source = gsInst.cardFilePath + '/' + gsInst.hand[ cPlayer]['cardid'][scatterID] box = gsInst.ids['showDownLabel'] anim = Animation(x=box.pos[0] + (box.width / 2) - (gsInst.ids['card0'].width / 2), y=box.pos[1] + (box.height / 2) - (gsInst.ids['card0'].height / 2), d=duration, t='out_quint') anim.bind(on_complete=setTmpActiveCard) anim.start(card) anim = Animation(x=int(gsInst.xpos_center), y=0 - gsInst.ids['card0'].size[1] * 2, d=duration, t='in_out_quad') anim.bind(on_complete=smallcardGone) sc = gsInst.ids['p' + str(cPlayer) + 'c' + str(scatterID) + 'Image'] Widget_ToTop(gsInst.ids['infoFloat'], sc) anim.start(sc) return True if gsInst.gameState['controlPlayer'] is None: Logger.info('Poker CPU play fired') #POKER PLAY handID = [] def Poker_Change_With_handID(): hID = self.Poker_Change( gsInst.hand[cPlayer]['cardid'], gsInst.gameState['roundNumber'], gsInst.setConfig['pokerRoundCount']) ##http://stackoverflow.com/questions/8447947/is-it-possible-to-modify-variable-in-python-that-is-in-outer-but-not-global-sc handID.append(hID[1]) return hID[0] #get dicarded cards discardList = None if gsInst.hand[cPlayer]['canDiscard'] is False: ##Powerless - end turn discardList = [] elif Poker_Change_With_handID() is True: Logger.info('handID = ' + str(handID)) ##Let's try to get a good poker hand discardList = self.Poker_Discards( gsInst.hand[cPlayer]['cardid'], gsInst.hand[cPlayer]['posindex'], handID[0]) else: ##Let's try to position ourselves for the showdown / posible chicago call discardList = self.Showdown_Discards( gsInst.hand[cPlayer]['cardid'], gsInst.hand[cPlayer]['posindex']) Logger.info('CPU discarding' + str(discardList)) if not discardList: ##If no discards Logger.info('ending from not discardList') gsInst.End_Turn() return False #deal in new cards Pos = gsInst.Position_Small_Card_Offscreen( gsInst.ids['p1c1Image'] ) ##offscreen position same for all (dealer dependant) def anim_callback(a, w): gsInst.gameState['discardFlag'] = True Logger.info('ending from not anim_callback') gsInst.End_Turn() for counter, scatterID in enumerate(discardList): gsInst.discardNumber[cPlayer].append(scatterID) gsInst.Deal_Cards( cPlayer, gsInst.hand[cPlayer]['cardid'][scatterID]) scW = gsInst.ids['p' + str(cPlayer) + 'c' + str(scatterID) + 'Image'] duration = 1 if Configed_Bool("General", "fastPlay") is True: duration = 0.5 anim = Animation(x=Pos[0], y=Pos[1], d=duration, t='in_out_quad') anim = anim + Animation( x=gsInst.smallCardPos[cPlayer - 1][scatterID][0], y=gsInst.smallCardPos[cPlayer - 1][scatterID][1], d=0.5, t='in_out_quad') #print str(counter) + ' ' + str(len(discardList)) if counter == len(discardList) - 1: if Configed_Bool( "General", "sound") is True and gsInst.init is False: def dealSound(dt): gsInst.drop_sound.play() Clock.schedule_once(dealSound, duration) anim.bind(on_complete=anim_callback) anim.start(scW) return True elif gsInst.gameState[ 'controlPlayer'] is not None and gsInst.gameState[ 'activeCard'] is not None and all( item == 'DONE' for item in gsInst.hand[cPlayer]['cardid']): Logger.critical( 'Player num = ' + str(cPlayer) + '. This should never happen, we are continuing a game where the CPU has played but not completed end_turn yet.' ) return None elif gsInst.gameState[ 'controlPlayer'] is not None and gsInst.gameState[ 'chicago'] < 0: Logger.info('CPU Chicago Q fired') #shall we call Chicago? if self.Chicago_Question(gsInst.setConfig, gsInst.hand, cPlayer) is True: Logger.info('CPU will play Chicago') gsInst.Call_Chicago() gsInst.Fun_Text( self.Strip_Player(gsInst.hand[cPlayer]['name']) + ' calls Chicago', None, 'yellow', 1.5) Logger.info( 'CPU_Play requested from CPU_Play itself (CPU Chicago Q fired)' ) self.Next_Play(gsInst) else: Logger.info('CPU will NOT play Chicago') gsInst.Skip_Chicago() return True elif gsInst.gameState['chicago'] == cPlayer: Logger.info('CPU Chicago CPU play fired') #Showdown and we have called Chicago Play_Card( self.Showdown_Turn_Self_Chicago( gsInst.hand[cPlayer]['cardid'])) elif gsInst.gameState['chicago'] > 0: Logger.info('OTHER Chicago CPU play fired') #Showdown and player gsInst.gameState['chicago'] has called Chicago scatterID = self.Showdown_Turn_Other_Chicago( gsInst.hand[cPlayer]['cardid'], gsInst.gameState['activeCard'], cPlayer) return Play_Card(scatterID) elif gsInst.gameState['chicago'] == 0: Logger.info('Showdown without Chicago CPU play fired') #Showdown with no Chicago inControl = False if cPlayer == gsInst.gameState['controlPlayer']: inControl = True scatterID = self.Showdown_Turn_No_Chicago( gsInst.hand[cPlayer]['cardid'], gsInst.gameState['activeCard'], inControl, cPlayer) return Play_Card(scatterID)
def on_stop(self): Logger.critical('App:I\'m dying!')
# conversion for BGR->RGB, BGR->RGBA format if data.fmt in ('bgr', 'bgra'): color[0], color[2] = color[2], color[0] return color def load(filename): '''Load an image''' return Image.load(filename) # load image loaders image_libs = [] if platform in ('macosx', 'ios'): image_libs += [('imageio', 'img_imageio')] image_libs += [('tex', 'img_tex'), ('dds', 'img_dds'), ('pygame', 'img_pygame'), ('pil', 'img_pil'), ('gif', 'img_gif')] libs_loaded = core_register_libs('image', image_libs) from os import environ if not 'KIVY_DOC' in environ and not libs_loaded: import sys Logger.critical('App: Unable to get any Image provider, abort.') sys.exit(1) # resolve binding. from kivy.graphics.texture import Texture, TextureRegion
from kivy._version import __version__, RELEASE as _KIVY_RELEASE, \ _kivy_git_hash, _kivy_build_date # internals for post-configuration __kivy_post_configuration = [] if platform == 'macosx' and sys.maxsize < 9223372036854775807: r = '''Unsupported Python version detected!: Kivy requires a 64 bit version of Python to run on OS X. We strongly advise you to use the version of Python that is provided by Apple (don't use ports, fink or homebrew unless you know what you're doing). See http://kivy.org/docs/installation/installation-macosx.html for details. ''' Logger.critical(r) if sys.version_info[0] == 2: Logger.critical( 'Unsupported Python version detected!: Kivy 2.0.0 and higher does not ' 'support Python 2. Please upgrade to Python 3, or downgrade Kivy to ' '1.11.0 - the last Kivy release that still supports Python 2.') def parse_kivy_version(version): """Parses the kivy version as described in :func:`require` into a 3-tuple of ([x, y, z], 'rc|a|b|dev|post', 'N') where N is the tag revision. The last two elements may be None. """ m = re.match( '^([0-9]+)\\.([0-9]+)\\.([0-9]+?)(rc|a|b|\\.dev|\\.post)?([0-9]+)?$',
def on_stop(self): Logger.critical('Adeus.')
def on_stop(self): ''' Tests for safe close. This will likely contain more function later as the app evolves. ''' Logger.critical('Goodbye!')