def resource_find(filename, use_cache=("KIVY_DOC_INCLUDE" not in os.environ)): '''Search for a resource in the list of paths. Use resource_add_path to add a custom path to the search. By default, results are cached for 60 seconds. This can be disabled using use_cache=False. .. versionchanged:: 2.1.0 `use_cache` parameter added and made True by default. ''' if not filename: return found_filename = None if use_cache: found_filename = Cache.get('kv.resourcefind', filename) if found_filename: return found_filename if filename[:8] == 'atlas://': found_filename = filename else: abspath_filename = abspath(filename) if exists(abspath_filename): found_filename = abspath(filename) else: for path in reversed(resource_paths): abspath_filename = abspath(join(path, filename)) if exists(abspath_filename): found_filename = abspath_filename break if not found_filename and filename.startswith("data:"): found_filename = filename if use_cache and found_filename: Cache.append('kv.resourcefind', filename, found_filename) return found_filename
def populate(self): self._textures = [] if __debug__: Logger.trace("Image: %r, populate to textures (%d)" % (self.filename, len(self._data))) for count in xrange(len(self._data)): # first, check if a texture with the same name already exist in the # cache uid = "%s|%s|%s" % (self.filename, self._mipmap, count) texture = Cache.get("kv.texture", uid) # if not create it and append to the cache if texture is None: imagedata = self._data[count] texture = Texture.create_from_data(imagedata, mipmap=self._mipmap) if not self._nocache: Cache.append("kv.texture", uid, texture) if imagedata.flip_vertical: texture.flip_vertical() # set as our current texture self._textures.append(texture) # release data if ask if not self.keep_data: self._data[count].release_data()
def populate(self): self._textures = [] fname = self.filename if __debug__: Logger.trace('Image: %r, populate to textures (%d)' % (fname, len(self._data))) for count in range(len(self._data)): # first, check if a texture with the same name already exist in the # cache chr = type(fname) uid = chr(u'%s|%d|%d') % (fname, self._mipmap, count) texture = Cache.get('kv.texture', uid) # if not create it and append to the cache if texture is None: imagedata = self._data[count] source = '{}{}|'.format( 'zip|' if fname.endswith('.zip') else '', self._nocache) imagedata.source = chr(source) + uid texture = Texture.create_from_data( imagedata, mipmap=self._mipmap) if not self._nocache: Cache.append('kv.texture', uid, texture) if imagedata.flip_vertical: texture.flip_vertical() # set as our current texture self._textures.append(texture) # release data if ask if not self.keep_data: self._data[count].release_data()
def tile_draw(self, nx, ny, tx, ty, sx, sy, zoom, bound): '''Draw a specific tile on the screen. Return False if the tile is not yet available.''' # nx, ny = index of tile # tx, ty = real position on scatter # sx, sy = real size on scatter # pzoom = current zoom level image = self.tileserver.get(nx, bound - ny - 1, zoom, self.maptype) if image in (None, False): return if not image.texture: Logger.exception('Returned image has no texture.') return if image.texture.wrap is None: image.texture.wrap = GL_CLAMP alpha = Cache.get('tileserver.tilesalpha', image.id) if alpha is None: alpha = 0 if image.loaded: # as soon as we have the image alpha += min(self._dt * 4, 1.0) # fade it in Cache.append('tileserver.tilesalpha', image.id, alpha) with self.canvas: Color(1, 1, 1, alpha) Rectangle(pos=(tx, ty), size=(sx, sy), texture=image.texture)
def LoadAtlas(self) -> None: """ Loads the atlas picture file(s) """ oAtlas: Atlas try: Logger.debug(u'TheScreen: Loading Skin Atlas') if not Globals.bIgnoreAtlas: if Globals.oFnAtlasSkin.Exists(): oAtlas = Atlas(Globals.oFnAtlasSkin.string) Cache.append('kv.atlas', Globals.oFnAtlasSkin.string, oAtlas) Logger.debug(u'TheScreen: Loading Definition Atlas') if Globals.oDefinitionPathes.oFnDefinitionAtlas.Exists(): oAtlas = Atlas( Globals.oDefinitionPathes.oFnDefinitionAtlas.string) Cache.append( 'kv.atlas', Globals.oDefinitionPathes.oFnDefinitionAtlas.string, oAtlas) except ParseError as e: ShowErrorPopUp(uTitle="Fatal Error", uMessage=LogError( uMsg=u'TheScreen: Fatal Error:Load Atlas', oException=e), bAbort=True) return None
def template(self, *args, **ctx): '''Create a specialized template using a specific context. .. versionadded:: 1.0.5 With template, you can construct custom widget from a kv lang definition by giving them a context. Check :ref:`Template usage <template_usage>`. ''' # Prevent naming clash with whatever the user might be putting into the # ctx as key. name = args[0] if not name in self.templates: raise Exception('Unknown <%s> template name' % name) baseclasses, defs, fn = self.templates[name] name, baseclasses key = '%s|%s' % (name, baseclasses) cls = Cache.get('kv.lang', key) if cls is None: rootwidgets = [] for basecls in baseclasses.split('+'): rootwidgets.append(Factory.get(basecls)) cls = ClassType(name, tuple(rootwidgets), {}) Cache.append('kv.lang', key, cls) widget = cls() self._push_widgets() self._push_ids() self.idmap = copy(global_idmap) self.idmap['root'] = widget self.idmap['ctx'] = QueryDict(ctx) self.build_item(widget, defs, is_rule=True) self._pop_ids() self._pop_widgets() return widget
def list_constants(self, shorten=True, show_indx=False): "List all env constants." consts = Cache.get(category='envcache', key='constants') if not consts: Logger.info("ENV: Building env constants list.") consts = [] i = 1 for k in sorted(self.env_dict.keys()): v = self.env_dict[k].strip() row = [] if show_indx: if shorten and len(v[:50]) > 50: row = (i, k,v[:50]) else: row = (k, v) consts.append(row) i += 1 # Cache constants Logger.info("ENV: Caching constants.") Cache.append(category='envcache', key='constants', obj=consts) else: Logger.info("ENV: Retrieved constants from cache.") return consts
def populate(self): self._textures = [] fname = self.filename if __debug__: Logger.trace('Image: %r, populate to textures (%d)' % (fname, len(self._data))) for count in range(len(self._data)): # first, check if a texture with the same name already exist in the # cache chr = type(fname) uid = chr(u'%s|%d|%d') % (fname, self._mipmap, count) texture = Cache.get('kv.texture', uid) # if not create it and append to the cache if texture is None: imagedata = self._data[count] source = '{}{}|'.format( 'zip|' if fname.endswith('.zip') else '', self._nocache) imagedata.source = chr(source) + uid texture = Texture.create_from_data(imagedata, mipmap=self._mipmap) if not self._nocache: Cache.append('kv.texture', uid, texture) if imagedata.flip_vertical: texture.flip_vertical() # set as our current texture self._textures.append(texture) # release data if ask if not self.keep_data: self._data[count].release_data()
def _set_filename(self, value): if value is None or value == self._filename: return self._filename = value # construct uid as a key for Cache uid = '%s|%s|%s' % (self.filename, self._mipmap, 0) # in case of Image have been asked with keep_data # check the kv.image cache instead of texture. image = Cache.get('kv.image', uid) if image: # we found an image, yeah ! but reset the texture now. self.image = image self._texture = None self._img_iterate() return else: # if we already got a texture, it will be automatically reloaded. _texture = Cache.get('kv.texture', uid) if _texture: self._texture = _texture return # if image not already in cache then load tmpfilename = self._filename self.image = ImageLoader.load(self._filename, keep_data=self._keep_data, mipmap=self._mipmap) self._filename = tmpfilename # put the image into the cache if needed Cache.append('kv.image', uid, self.image)
def scan_qr(self, on_complete): dlg = Cache.get('electrum_widgets', 'QrScannerDialog') if not dlg: dlg = Factory.QrScannerDialog() Cache.append('electrum_widgets', 'QrScannerDialog', dlg) dlg.bind(on_complete=on_complete) dlg.open()
def template(self, *args, **ctx): '''Create a specialized template using a specific context. .. versionadded:: 1.0.5 With templates, you can construct custom widgets from a kv lang definition by giving them a context. Check :ref:`Template usage <template_usage>`. ''' # Prevent naming clash with whatever the user might be putting into the # ctx as key. name = args[0] if name not in self.templates: raise Exception('Unknown <%s> template name' % name) baseclasses, rule, fn = self.templates[name] key = '%s|%s' % (name, baseclasses) cls = Cache.get('kv.lang', key) if cls is None: rootwidgets = [] for basecls in baseclasses.split('+'): rootwidgets.append(Factory.get(basecls)) cls = type(name, tuple(rootwidgets), {}) Cache.append('kv.lang', key, cls) widget = cls() # in previous versions, ``ctx`` is passed as is as ``template_ctx`` # preventing widgets in it from be collected by the GC. This was # especially relevant to AccordionItem's title_template. proxy_ctx = {k: get_proxy(v) for k, v in ctx.items()} self._apply_rule(widget, rule, rule, template_ctx=proxy_ctx) return widget
def tile_draw(self, nx, ny, tx, ty, sx, sy, zoom, bound): '''Draw a specific tile on the screen. Return False if the tile is not yet available.''' # nx, ny = index of tile # tx, ty = real position on scatter # sx, sy = real size on scatter # pzoom = current zoom level image = self.tileserver.get(nx, bound-ny-1, zoom, self.maptype) if image in (None, False): return if not image.texture: Logger.exception('Returned image has no texture.') return if image.texture.wrap is None: image.texture.wrap = GL_CLAMP alpha = Cache.get('tileserver.tilesalpha', image.id) if alpha is None: alpha = 0 if image.loaded: # as soon as we have the image alpha += min(self._dt * 4, 1.0) # fade it in Cache.append('tileserver.tilesalpha', image.id, alpha) with self.canvas: Color(1, 1, 1, alpha) Rectangle(pos=(tx, ty), size=(sx, sy), texture=image.texture)
def gen_cards(self): """ Method which generate cards with ico projects description. :return: """ # Check for active category button. if self.last_category_btn is None: self.upcoming._active = True self.grid_box.bind(minimum_height=self.grid_box.setter('height')) # Get active category. cat = self.last_category_btn.text.lower() if self.last_category_btn is not None \ else self.upcoming.text.lower() # Get url content. url = 'http://127.0.0.1:8000/ico/icobazaar&cat={}&limit=150&skip=0'.format( cat) icos_lst = utils.get_url_content(url) # Clear widgets and generate cards. self.grid_box.clear_widgets() import gc gc.collect() for ico_data in icos_lst: card = CardIcoBazaar(ico_data) self.grid_box.add_widget(card) # Set categories box object into cache. Cache.register('menu_cats_box') Cache.append('menu_cats_box', 'cats_box_obj', self.cats_box)
def populate(self): self._textures = [] if __debug__: Logger.trace('Image: %r, populate to textures (%d)' % (self.filename, len(self._data))) for count in xrange(len(self._data)): # first, check if a texture with the same name already exist in the # cache uid = '%s|%s|%s' % (self.filename, self._mipmap, count) texture = Cache.get('kv.texture', uid) # if not create it and append to the cache if texture is None: texture = Texture.create_from_data( self._data[count], mipmap=self._mipmap) Cache.append('kv.texture', uid, texture) # set as our current texture self._textures.append(texture) # release data if ask if not self.keep_data: self._data[count].release_data()
def image(self, filename, load_callback=None, post_callback=None, **kwargs): '''Load a image using loader. A Proxy image is returned with a loading image. :: img = Loader.image(filename) # img will be a ProxyImage. # You'll use it the same as an Image class. # Later, when the image is really loaded, # the loader will change the img.image property # to the new loaded image ''' data = Cache.get('kivy.loader', filename) if data not in (None, False): # found image, if data is not here, need to reload. return ProxyImage(data, loading_image=self.loading_image, loaded=True, **kwargs) client = ProxyImage(self.loading_image, loading_image=self.loading_image, **kwargs) self._client.append((filename, client)) if data is None: # if data is None, this is really the first time self._q_load.append((filename, load_callback, post_callback)) Cache.append('kivy.loader', filename, False) self._start_wanted = True self._trigger_update() else: # already queued for loading pass return client
def _update(self, *largs): '''(internal) Check if a data is loaded, and pass to the client.''' # want to start it ? if self._start_wanted: if not self._running: self.start() self._start_wanted = False # in pause mode, don't unqueue anything. if self._paused: self._trigger_update() return for x in range(self.max_upload_per_frame): try: filename, data = self._q_done.pop() except IndexError: return # create the image image = data # ProxyImage(data) if not image.nocache: Cache.append('kv.loader', filename, image) # update client for c_filename, client in self._client[:]: if filename != c_filename: continue # got one client to update client.image = image client.loaded = True client.dispatch('on_load') self._client.remove((c_filename, client)) self._trigger_update()
def _update(self, *largs): '''(internal) Check if a data is loaded, and pass to the client''' # want to start it ? if self._start_wanted: if not self._running: self.start() self._start_wanted = False while True: try: filename, data = self._q_done.pop() except IndexError: return # create the image image = data#ProxyImage(data) Cache.append('kivy.loader', filename, image) # update client for c_filename, client in self._client[:]: if filename != c_filename: continue # got one client to update client.image = image client.loaded = True client.dispatch('on_load') self._client.remove((c_filename, client))
def on_pic_select(self, widget_name, file_path, mouse_pos): """ This method uploads selected picture to server and updates related widgets on GUI. :param self: It is for handling class structure. :param widget_name: It is for handling file chooser input. :param file_path: It is path of selected file. :param mouse_pos: It is for handling file chooser input. :return: """ self.popup.dismiss() database_api.uploadProfilePic(Cache.get("info", "token"), Cache.get("info", "nick"), file_path[0] ) if round_image.update_image(): Cache.append("info", "pict", True ) pic = [self.ico_user_picture, self.ids["img_user_card"] ] for pp in pic: pp.source = "data/img/pic_user_current.png" pp.reload()
def populate(self): self._textures = [] if __debug__: Logger.trace('Image: %r, populate to textures (%d)' % (self.filename, len(self._data))) for count in range(len(self._data)): # first, check if a texture with the same name already exist in the # cache uid = '%s|%s|%s' % (self.filename, self._mipmap, count) texture = Cache.get('kv.texture', uid) # if not create it and append to the cache if texture is None: imagedata = self._data[count] texture = Texture.create_from_data(imagedata, mipmap=self._mipmap) if not self._nocache: Cache.append('kv.texture', uid, texture) if imagedata.flip_vertical: texture.flip_vertical() # set as our current texture self._textures.append(texture) # release data if ask if not self.keep_data: self._data[count].release_data()
def template(self, *args, **ctx): '''Create a specialized template using a specific context. .. versionadded:: 1.0.5 With template, you can construct custom widget from a kv lang definition by giving them a context. Check :ref:`Template usage <template_usage>`. ''' # Prevent naming clash with whatever the user might be putting into the # ctx as key. name = args[0] if name not in self.templates: raise Exception('Unknown <%s> template name' % name) baseclasses, rule, fn = self.templates[name] key = '%s|%s' % (name, baseclasses) cls = Cache.get('kv.lang', key) if cls is None: rootwidgets = [] for basecls in baseclasses.split('+'): rootwidgets.append(Factory.get(basecls)) cls = ClassType(name, tuple(rootwidgets), {}) Cache.append('kv.lang', key, cls) widget = cls() self._apply_rule(widget, rule, rule, template_ctx=ctx) return widget
def build_config(self, config): config.setdefaults('appearance', { 'window_height': 1080, 'window_width': 1920, }) config.setdefaults('video_settings', { 'frames': 30 }) config.setdefaults('video_settings', { 'video_path': os.getcwd() }) config.setdefaults('detector', { 'detection_certainty': 90, }) config.setdefaults('reader', { 'reading_certainty': 95, }) config.setdefaults('reader', { 'max_similar_readings': 10, }) config.setdefaults('database', { 'database_path': os.path.join(os.getcwd(), 'platedb'), }) # Put config object into the cache so it can be used outside Cache.append('cache', 'config', config)
def _set_filename(self, value): if value is None or value == self._filename: return self._filename = value # construct uid as a key for Cache uid = '%s|%s|%s' % (self.filename, self._mipmap, 0) keep_data = self._keep_data # in case of Image have been asked with keep_data # check the kv.image cache instead of texture. if keep_data: image = Cache.get('kv.image', uid) if image: # we found an image, yeah ! but reset the texture now. self.image = image self._texture = None self._img_iterate() return else: # if we already got a texture, it will be automatically reloaded. _texture = Cache.get('kv.texture', uid) if _texture: return # if image not already in cache then load tmpfilename = self._filename self.image = ImageLoader.load( self._filename, keep_data=self._keep_data, mipmap=self._mipmap) self._filename = tmpfilename # put the image into the cache if needed if keep_data: Cache.append('kv.image', uid, self.image)
def _got_rfid_token(request, result): Logger.debug("HMS: get_rfid_token: got new rfid token") self._rfid_token_request = None result["expires_at"] = time() + result["expires_in"] Cache.append("HMS", "rfid_token", result, result["expires_in"]) if on_success: on_success(request, result)
def __init__(self, filename, **kwargs): self.filename = filename self.svg_data = Cache.get("kivy.svg", filename) if not self.svg_data: new_svg = self.load(filename) Cache.append("kivy.svg", filename, new_svg) self.svg_data = new_svg
def on_edit(self, no, dt): self.popup.dismiss() Cache.append("lect", "exam", self.ids["txt_info_head"].text) Cache.append("lect", "question", no) pages.append(EduEdit(name="EduEdit")) appReset.on_back(pages, screen)
def on_stats_target(target): select = Cache.get("info", "id") Cache.append("data", "type", target) Cache.append("data", "select", select) pages.append(StdStats(name="StdStats")) appReset.on_back(pages, screen)
def __getitem__(self, item): if not self._loaded_textures[item]: # first, check if a texture with the same name already exist in the # cache # pylint: disable-msg=redefined-builtin chr = type(self._filename) uid = chr(u'%s|%d|%d') % (self._filename, self._mipmap, item) texture = Cache.get('kv.texture', uid) # if not create it and append to the cache if texture is None: zfilename = self._index_list[item] # read file and store it in mem with fileIO struct around it tmpfile = BytesIO(self._zip_file.read(zfilename)) ext = zfilename.split('.')[-1].lower() image = None for loader in ImageLoader.loaders: if (ext not in loader.extensions() or not loader.can_load_memory()): continue Logger.debug('Image%s: Load <%s> from <%s>', loader.__name__[11:], zfilename, self._filename) try: image = loader(zfilename, ext=ext, rawdata=tmpfile, inline=True) except: # pylint: disable-msg=bare-except # noqa # Loader failed, continue trying. continue break if image is None: raise AssertionError("Could not load image {} (index {}) " "from zip {}".format( zfilename, item, self._filename)) self.width = image.width self.height = image.height imagedata = image._data[ 0] # pylint: disable-msg=protected-access source = '{}{}|'.format( 'zip|' if self._filename.endswith('.zip') else '', self._no_cache) imagedata.source = chr(source) + uid texture = Texture.create_from_data(imagedata, mipmap=self._mipmap) if not self._no_cache: Cache.append('kv.texture', uid, texture) if imagedata.flip_vertical: texture.flip_vertical() self._loaded_textures[item] = texture return self._loaded_textures[item]
def callback(self): weekNumber = int(self.text.split()[-1]) if Cache.get("counter", 'value') == None: Cache.append("counter", 'value', weekNumber) else: Cache.remove("counter", "value") Cache.append("counter", 'value', weekNumber) pages.append(UserAttendance(name="UserAttendance")) Functions.ChangePage(pages, screen)
def image(self, filename, load_callback=None, post_callback=None, **kwargs): '''Load a image using the Loader. A ProxyImage is returned with a loading image. You can use it as follows:: from kivy.app import App from kivy.uix.image import Image from kivy.loader import Loader class TestApp(App): def _image_loaded(self, proxyImage): if proxyImage.image.texture: self.image.texture = proxyImage.image.texture def build(self): proxyImage = Loader.image("myPic.jpg") proxyImage.bind(on_load=self._image_loaded) self.image = Image() return self.image TestApp().run() In order to cancel all background loading, call *Loader.stop()*. ''' data = Cache.get('kv.loader', filename) if data not in (None, False): # found image, if data is not here, need to reload. return ProxyImage(data, loading_image=self.loading_image, loaded=True, **kwargs) client = ProxyImage(self.loading_image, loading_image=self.loading_image, **kwargs) self._client.append((filename, client)) if data is None: # if data is None, this is really the first time self._q_load.appendleft({ 'filename': filename, 'load_callback': load_callback, 'post_callback': post_callback, 'kwargs': kwargs }) if not kwargs.get('nocache', False): Cache.append('kv.loader', filename, False) self._start_wanted = True self._trigger_update() else: # already queued for loading pass return client
def set_app(self): Cache.register('bike') Cache.register('map') Cache.remove('bike', 'rm') Cache.append('bike', 'rm', RM) self.sm = ScreenManager(transition=WipeTransition()) self.sm.add_widget(MenuScreen(name='menu')) self.sm.add_widget(GameScreen(name='game')) self.render(self.sm)
def show_tx_details(self, item): ra_dialog = Cache.get('electrum_widgets', 'RecentActivityDialog') if not ra_dialog: Factory.register('RecentActivityDialog', module='electrum_gui.kivy.uix.dialogs.carousel_dialog') Factory.register('GridView', module='electrum_gui.kivy.uix.gridview') ra_dialog = ra_dialog = Factory.RecentActivityDialog() Cache.append('electrum_widgets', 'RecentActivityDialog', ra_dialog) ra_dialog.item = item ra_dialog.open()
def on_stats_target(self, target): if target == "student": select = self.ids["txt_id_body"].text else: select = self.ids["txt_lect_code"].text Cache.append("data", "type", target) Cache.append("data", "select", select) pages.append(EduStats(name="EduStats")) appReset.on_back(pages, screen)
def on_source(self, instance, value): if not value: self.texture = None else: filename = resource_find(value) texture = Cache.get('kv.texture', filename) if not texture: image = CoreImage(filename) texture = image.texture Cache.append('kv.texture', filename, texture) self.texture = texture
def on_success(request, response): response = json.loads(response) try: hrate = response['bpi'][mintime] hrate = abs(btc_amt) * decimal.Decimal(hrate) Cache.append('history_rate', uid, hrate) except KeyError: hrate = 'not found' self.parent.set_history_rate(item, hrate)
def get_atlas(atlas_path): """ Get atlas from the Kivy cache if present, otherwise initialize it """ from kivy.atlas import Atlas from kivy.cache import Cache atlas = Cache.get('kv.atlas', atlas_path.replace('atlas://', '')) if not atlas: logger.info(f'Initializing atlas "{atlas_path}"') atlas = Atlas(f'{atlas_path}.atlas') Cache.append('kv.atlas', atlas_path, atlas) return atlas
def _set_filename(self, value): #Logger.info('CoreImageOpenCV: value %s' % (value)) if value is None or value == self._filename: return self._filename = value # construct uid as a key for Cache if (self.res_width > 0) or (self.res_height > 0): uid = '%s|%d|%d|%s|%s' % (self.filename, self.res_width, self.res_height, self._mipmap, 0) else: uid = '%s|%s|%s' % (self.filename, self._mipmap, 0) # in case of Image have been asked with keep_data # check the kv.image cache instead of texture. image = Cache.get('kv.image', uid) if image: # we found an image, yeah ! but reset the texture now. self.image = image # if image.__class__ is core image then it's a texture # from atlas or other sources and has no data so skip if (image.__class__ != self.__class__ and not image.keep_data and self._keep_data): self.remove_from_cache() self._filename = '' self._set_filename(value) else: self._texture = None self._img_iterate() return else: # if we already got a texture, it will be automatically reloaded. _texture = Cache.get('kv.texture', uid) if _texture: self._texture = _texture return # if image not already in cache then load tmpfilename = self._filename #Logger.info('CoreImageOpenCV: set_filename %s' % (tmpfilename)) #Logger.info('CoreImageOpenCV: %d %d' % (self.res_width, self.res_height)) image = ImageLoader.load( self._filename, keep_data=self._keep_data, mipmap=self._mipmap, nocache=self._nocache, res_width=self.res_width, res_height=self.res_height, load_exif=self.load_exif) self._filename = tmpfilename # put the image into the cache if needed if isinstance(image, Texture): self._texture = image self._size = image.size else: self.image = image if not self._nocache: Cache.append('kv.image', uid, self.image)
def update(self): '''Must be called to get pull image from the workers queue ''' pop = self.q_out.pop while True: try: filename, image = pop() self.q_count -= 1 except: return Cache.append('tileserver.tiles', filename, image)
def _create_line_label(self, text): # Create a label from a text, using line options ntext = text.replace('\n', '').replace('\t', ' ' * self.tab_width) kw = self._get_line_options() cid = '%s\0%s' % (ntext, str(kw)) texture = Cache.get('textinput.label', cid) if not texture: label = Label(text=ntext, **kw) label.refresh() texture = label.texture Cache.append('textinput.label', cid, texture) return texture
def _create_line_label(self, text): # Create a label from a text, using line options ntext = text.replace("\n", "").replace("\t", " " * self.tab_width) kw = self._get_line_options() cid = "%s\0%s" % (ntext, str(kw)) texture = Cache.get("textinput.label", cid) if not texture: label = Label(text=ntext, **kw) label.refresh() texture = label.texture Cache.append("textinput.label", cid, texture) return texture
def set_char_screen(self, character, support, resolve, direction='right'): if character == self._displayed_character and support == self._displayed_support: return if resolve: self.dispatch('on_resolve', character, support) return self._displayed_character, self._displayed_support = character, support if not self.is_select: self.dispatch('on_party_change', character, support) char = Refs.gc.get_char_by_index(character) supt = Refs.gc.get_char_by_index(support) name = char.get_id() if supt is not None: name += '_' + supt.get_id() screen = Cache.get('preview.slides', name) in_cache = screen is not None if in_cache and screen.parent is not None: screen = None old_screen = self.current_screen if screen is None: screen = FilledCharacterPreviewScreen(is_support=False, character=character, support=support, size_hint=(None, None)) preview = screen.get_root() preview.bind(on_select=self.on_select_screen) preview.bind(on_attr=self.on_attr_screen) preview.bind(on_empty=self.on_remove) screen.size = self.size if not in_cache: Cache.append('preview.slides', name, screen) screen.locked = self.locked screen.displayed = self.displayed screen.support_displayed = self.support_displayed if direction is None: self.transition = NoTransition() else: self.transition = SlideTransition() self.transition.direction = direction self.switch_to(screen) if old_screen and old_screen != 'empty': self.remove_widget(old_screen)
def texture_update(self, *largs): if not self.source: self.texture = None else: filename = resource_find(self.source) mipmap = self.mipmap uid = '%s|%s' % (filename, mipmap) texture = Cache.get('kv.texture', uid) if not texture: image = CoreImage(filename, mipmap=mipmap) texture = image.texture Cache.append('kv.texture', uid, texture) self.texture = texture
def image(self, filename, load_callback=None, post_callback=None, **kwargs): '''Load a image using the Loader. A ProxyImage is returned with a loading image. You can use it as follows:: from kivy.app import App from kivy.uix.image import Image from kivy.loader import Loader class TestApp(App): def _image_loaded(self, proxyImage): if proxyImage.image.texture: self.image.texture = proxyImage.image.texture def build(self): proxyImage = Loader.image("myPic.jpg") proxyImage.bind(on_load=self._image_loaded) self.image = Image() return self.image TestApp().run() In order to cancel all background loading, call *Loader.stop()*. ''' data = Cache.get('kv.loader', filename) if data not in (None, False): # found image, if data is not here, need to reload. return ProxyImage(data, loading_image=self.loading_image, loaded=True, **kwargs) client = ProxyImage(self.loading_image, loading_image=self.loading_image, **kwargs) self._client.append((filename, client)) if data is None: # if data is None, this is really the first time self._q_load.appendleft({ 'filename': filename, 'load_callback': load_callback, 'post_callback': post_callback, 'kwargs': kwargs}) if not kwargs.get('nocache', False): Cache.append('kv.loader', filename, False) self._start_wanted = True self._trigger_update() else: # already queued for loading pass return client
def _get_text_width(self, text): # fix cursor placement diff cause of markup kw = self._line_options ntext = text.replace('\t', ' ' * self.tab_width) cid = '%s\0%s' % (ntext, str(kw)) width = Cache.get('textinput.label.width', cid) if not width: texture = self._create_line_label(ntext) # use width of texture of '.' instead of ' ' in start of line, # which is of 0 width in markup width = texture.width if texture else\ self._label_cached.get_extents('.')[0] * len(ntext) Cache.append('codeinput.label.width', cid, width) return width
def texture_update(self, *largs): if not self.source: self.texture = None else: filename = resource_find(self.source) if filename is None: return mipmap = self.mipmap uid = "%s|%s" % (filename, mipmap) texture = Cache.get("kv.texture", uid) if not texture: image = CoreImage(filename, mipmap=mipmap) texture = image.texture Cache.append("kv.texture", uid, texture) self.texture = texture
def init_ui(self): ''' Initialize The Ux part of electrum. This function performs the basic tasks of setting up the ui. ''' global ref if not ref: from weakref import ref set_language(self.electrum_config.get('language')) self.funds_error = False self.completions = [] # setup UX self.screens = ['mainscreen',] #setup lazy imports for mainscreen Factory.register('AnimatedPopup', module='electrum_gui.kivy.uix.dialogs') Factory.register('TabbedCarousel', module='electrum_gui.kivy.uix.screens') Factory.register('ScreenDashboard', module='electrum_gui.kivy.uix.screens') #Factory.register('EffectWidget', # module='electrum_gui.kivy.uix.effectwidget') Factory.register('QRCodeWidget', module='electrum_gui.kivy.uix.qrcodewidget') Factory.register('MainScreen', module='electrum_gui.kivy.uix.screens') Factory.register('CSpinner', module='electrum_gui.kivy.uix.screens') # preload widgets. Remove this if you want to load the widgets on demand Cache.append('electrum_widgets', 'AnimatedPopup', Factory.AnimatedPopup()) Cache.append('electrum_widgets', 'TabbedCarousel', Factory.TabbedCarousel()) Cache.append('electrum_widgets', 'QRCodeWidget', Factory.QRCodeWidget()) Cache.append('electrum_widgets', 'CSpinner', Factory.CSpinner()) # load and focus the ui #Load mainscreen dr = Builder.load_file('gui/kivy/uix/ui_screens/mainscreen.kv') self.root.add_widget(dr) self.root.manager = manager = dr.ids.manager self.root.main_screen = m = manager.screens[0] self.tabs = m.ids.tabs #TODO # load left_menu self.icon = "icons/electrum.png" # connect callbacks if self.network: self.network.register_callback('updated', self._trigger_update_wallet) self.network.register_callback('status', self._trigger_update_status) self.network.register_callback('new_transaction', self._trigger_notify_transactions) self.wallet = None
def _set_filename(self, value): if value is None or value == self._filename: return self._filename = value # construct uid as a key for Cache f = self.filename uid = type(f)(u'%s|%d|%d') % (f, self._mipmap, 0) # in case of Image have been asked with keep_data # check the kv.image cache instead of texture. image = Cache.get('kv.image', uid) if image: # we found an image, yeah ! but reset the texture now. self.image = image # if image.__class__ is core image then it's a texture # from atlas or other sources and has no data so skip if (image.__class__ != self.__class__ and not image.keep_data and self._keep_data): self.remove_from_cache() self._filename = '' self._set_filename(value) else: self._texture = None return else: # if we already got a texture, it will be automatically reloaded. _texture = Cache.get('kv.texture', uid) if _texture: self._texture = _texture return # if image not already in cache then load tmpfilename = self._filename image = ImageLoader.load( self._filename, keep_data=self._keep_data, mipmap=self._mipmap, nocache=self._nocache) self._filename = tmpfilename # put the image into the cache if needed if isinstance(image, Texture): self._texture = image self._size = image.size else: self.image = image if not self._nocache: Cache.append('kv.image', uid, self.image)
def _create_line_label(self, text): #TODO: optimize this func, it's horribly inefficient ntext = text.replace('\n', '').replace('\t', ' ' * self.tab_width) # Create a label from a text, using line options kw = self._line_options cid = '%s\0%s' % (ntext, str(kw)) texture = Cache.get('codeinput.label', cid) if not texture: #if multiple lines render empty texture wait for refresh text' if text.find('\n') > 0: label = self._label_cached label.text = '' label.refresh() texture = label.texture Cache.append('codeinput.label', cid, texture) return texture #get bbcoded text for python try: ntext[0] # replace brackets with special chars that aren't highlighted # by pygment. can't use &bl; ... cause & is highlighted # if at some time support for braille is added then replace these # characters with something else ntext = ntext.replace('[', u'⣿;').replace(']', u'⣾;') ntext = highlight(ntext, self.lexer, self.formatter) ntext = ntext.replace(u'⣿;', '&bl;').replace(u'⣾;', '&br;') # replace special chars with &bl; and &br; ntext = ''.join(('[color=rgba', str(self.text_color), ']', ntext, '[/color]')) except IndexError: pass # FIXME right now, we can't render very long line... # if we move on "VBO" version as fallback, we won't need to do this. # try to found the maximum text we can handle label = self._markup_label_cached label.text = ntext label.texture_update() texture = label.texture label.text = '' Cache.append('codeinput.label', cid, texture) return texture
def _img_iterate(self, *largs): # Purpose: check if image has sequences then animate self._iteration_done = True imgcount = count = 0 if self.image: imgcount = len(self.image._data) # get texture for first image from cache uid = '%s|%s|%s' % (self.filename, self._mipmap, count) _texture = Cache.get('kv.texture', uid) if not _texture: # if texture is not in cache while count < imgcount: # append the sequence of images to cache _texture= Texture.create_from_data( self.image._data[count], mipmap=self._mipmap) if not self.image.keep_data: # release excess memory self.image._data[count].release_data() # Cache texture Cache.append('kv.texture', uid, _texture) count += 1 uid = '%s|%s|%s' % (self.filename, self._mipmap, count) else: # texture already in cache for first image # assign texture for non sequenced cached images self._texture = _texture self._size = self.texture.size # check if image has sequence in cache uid = '%s|%s|%s' % (self.filename, self._mipmap, 1) # get texture for second image in sequence _texture_next = Cache.get('kv.texture', uid) if _texture_next: # enable animation (cached sequence img) imgcount = 2 _texture = _texture_next if imgcount > 1: self._anim_available = True # image sequence, animate self.anim_reset(True) self._texture = _texture # image loaded for the first time if self.image: self.image._texture = self._texture = _texture
def get(self, nx, ny, zoom, maptype, format='png'): '''Get a tile ''' filename = self.to_filename(nx, ny, zoom, maptype, format) img = Cache.get('tileserver.tiles', filename) # check if the tile is already being loaded if img is False: return None # check if the tile exist in the cache if img is not None: return img # no tile, ask to workers to download Cache.append('tileserver.tiles', filename, False) self.q_count += 1 self.q_in.append((nx, ny, zoom, maptype, format)) self.c_in.acquire() self.c_in.notify() self.c_in.release() return None