def load_zipimage(self, source, frames): # keep running the test until loaded (or timeout) maxfps = self.maxfps timeout = 30 * maxfps # load ZIP with images named: 000.png, 001.png, ... image = AsyncImage( source=source, anim_delay=0.0333333333333333 ) image.test_loaded = False self.render(image) # bind to 'on_load' because there are various # steps where the image is (re)loaded, but # the event is triggered only at the end image.bind(on_load=lambda *_, **__: setattr( image, 'test_loaded', True )) while timeout and not image.test_loaded: self.advance_frames(1) timeout -= 1 proxyimg = image._coreimage self.assertTrue(proxyimg.anim_available) self.assertEqual(len(proxyimg.image.textures), frames) return image
def test_reload_asyncimage(self): from kivy.resources import resource_find from kivy.uix.image import AsyncImage temp_dir = mkdtemp() event = Event() image = AsyncImage() image.bind(on_load=lambda *args, **kwargs: event.set()) fn = resource_find('data/logo/kivy-icon-16.png') source = join(temp_dir, 'source.png') copyfile(fn, source) event.clear() image.source = source self.wait_for_event_or_timeout(event) self.render(image, framecount=2) self.assertEqual(image.texture_size, [16, 16]) remove(source) fn = resource_find('data/logo/kivy-icon-32.png') copyfile(fn, source) event.clear() image.reload() self.wait_for_event_or_timeout(event) self.render(image, framecount=2) self.assertEqual(image.texture_size, [32, 32]) remove(source) rmtree(temp_dir)
class ShowAPhoto(BoxLayout): def __init__(self, **kwargs): super(ShowAPhoto,self).__init__(**kwargs) self.prepare_image_list() self.add_image_widget() self.register_keydown_event() def prepare_image_list(self): if(images_finder.is_images_contained(sys.argv)) : image_arg = images_finder.find_fist_images_in_list(sys.argv) self.prepare_list(image_arg) else: self.prepare_list('./') def add_image_widget(self): self.aimage = AsyncImage(source=self.get_next_file()) self.aimage.bind(source=self._on_image_load) self.add_widget(self.aimage) def register_keydown_event(self): self._keyboard = Window.request_keyboard(self._keyboard_closed, self, 'text') self._keyboard.bind(on_key_down=self._on_keyboard_down) def _on_image_load(self,image,source): self.set_app_title(source) def set_app_title(self, title): EventLoop.window.title = title def prepare_list(self,filepath): folderpath = os.path.dirname(filepath)+'/' file_list = images_finder.list_all_images_in_folder(folderpath) iterator= bidirection_iterator.BidirectionIterator(file_list) if filepath != './': iterator.move_before(filepath) self.file_iterator = iterator def get_next_file(self): return self.file_iterator.next() def get_previous_file(self): return self.file_iterator.previous() def _keyboard_closed(self): print('My keyboard have been closed') self._keyboard.unbind(on_key_down=self._on__keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): if keycode[1] == 'left': self.aimage.source = self.get_previous_file() else: self.aimage.source = self.get_next_file()
class Container(Widget): source = ObjectProperty() image = ObjectProperty() def __init__(self, source, **kwargs): super().__init__(**kwargs) self.image = AsyncImage() self.loader_clock = Clock.schedule_interval(self.adjust_size, self.image.anim_delay) self.image.bind(on_load=lambda inst: ( self.adjust_size(), self.loader_clock.cancel(), )) self.source = source self.bind(size=self.adjust_size, pos=self.adjust_size) def on_source(self, instance, value): if isinstance(value, str): self.image.source = value else: self.image.texture = value self.adjust_size() def adjust_size(self, *args): if not self.parent or not self.image.texture: return (par_x, par_y) = self.parent.size if par_x == 0 or par_y == 0: with self.canvas: self.canvas.clear() return par_scale = par_x / par_y (img_x, img_y) = self.image.texture.size img_scale = img_x / img_y if par_scale > img_scale: (img_x_new, img_y_new) = (img_x, img_x / par_scale) else: (img_x_new, img_y_new) = (img_y * par_scale, img_y) crop_pos_x = (img_x - img_x_new) / 2 crop_pos_y = (img_y - img_y_new) / 2 subtexture = self.image.texture.get_region(crop_pos_x, crop_pos_y, img_x_new, img_y_new) with self.canvas: self.canvas.clear() Color(1, 1, 1) Rectangle(texture=subtexture, pos=self.pos, size=(par_x, par_y))
class PhotoStrip(ScrollView): def on_press(self, filename): pass def on_release(self, filename): pass def __init__(self, *args, **kwargs): super(PhotoStrip, self).__init__(size_hint=(1,1), pos_hint={'center_x': 0.5, 'center_y': 0.5}, do_scroll_x=False, *args, **kwargs) self.register_event_type('on_press') self.register_event_type('on_release') self.strip = AsyncImage(source='photos-strip.png', allow_stretch=True, size_hint_y=1.8) self.add_widget(self.strip) self.image0 = image_button() self.image0.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image0) self.image1 = image_button() self.image1.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image1) self.image2 = image_button() self.image2.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image2) self.image3 = image_button() self.image3.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image3) self.strip.bind(size=self.update_buttons,pos=self.update_buttons) def set_path(self, path): print path path = filesystem.normpath(path) print path self.scroll_y = 1 if 'effect_y' in dir(self): # Kivy 1.6.0 doesn't have effect_y self.effect_y.value = self.effect_y.min # This is to work around a bug with the ScrollView (https://github.com/kivy/kivy/issues/2038) self.image0.source = filesystem.join(path, '0.jpg') self.image1.source = filesystem.join(path, '1.jpg') self.image2.source = filesystem.join(path, '2.jpg') self.image3.source = filesystem.join(path, 'blank') def press_btn(self, btn): self.dispatch('on_press', btn.source) def release_btn(self, btn): self.dispatch('on_release', btn.source) def update_buttons(self, instance, value): spacing = 20 padding = 25 offset = padding for img in [self.image0, self.image1, self.image2, self.image3]: img.size = (instance.norm_image_size[0]/60)*43, (instance.norm_image_size[1]-((spacing*3)+(padding*2)))/4 img.center_x = instance.center_x img.center_y = instance.top-((img.height/2)+offset) offset += img.height+spacing
def callback(self): def update_height(img, *args): img.height = img.width / img.image_ratio dirpath = sys.argv[1] files = glob.glob(os.path.join(dirpath, '*.*')) btn = Button(text="Test", size_hint_y=None, height=100) btn.bind(on_press= lambda x: Popen('python LCDNet.py')) self.ids.wall.add_widget(btn) for f in files: image = AsyncImage(source=f, size_hint=(1, None), keep_ratio=True, allow_stretch=True) image.bind(width=update_height, image_ratio=update_height) self.ids.wall.add_widget(image)
def load_zipimage(self, source, frames): # load ZIP with images named: 000.png, 001.png, ... from kivy.uix.image import AsyncImage event = Event() image = AsyncImage(anim_delay=0.0333333333333333) # bind to 'on_load' because there are various # steps where the image is (re)loaded, but # the event is triggered only at the end image.bind(on_load=lambda *args, **kwargs: event.set()) image.source = source self.wait_for_event_or_timeout(event) self.render(image) proxyimg = image._coreimage self.assertTrue(proxyimg.anim_available) self.assertEqual(len(proxyimg.image.textures), frames) return image
def __init__(self, **kwargs): # get any files into images directory self.injectWidget = kwargs.get("injectWidget") self.source = kwargs.get("source") #curdir = dirname(__file__) # backward # path = os.getcwd() # print(os.path.abspath(os.path.join(path, os.pardir))) picture1 = AsyncImage(source=self.source, size_hint=(1, 1)) with picture1.canvas.before: Color(0.3, 0.3, 0.4, 1) picture1.rect = Rectangle(size=picture1.size, pos=picture1.pos) def update_rect(instance, value): instance.rect.pos = instance.pos instance.rect.size = instance.size self.injectWidget.add_widget(picture1) picture1.bind(pos=update_rect, size=update_rect)
def selfUpdate(self, loadAssetElements): alllocalBox = BoxLayout(size_hint=(1, None), height=len(loadAssetElements) * 90, orientation='vertical') for _index, item in enumerate(loadAssetElements): localBox = BoxLayout(size_hint=(1, None), height=90, orientation='horizontal') currentColor = (self.engineConfig.getThemeBgSceneBtnColor()) if item['type'] == 'ImageResource': currentColor = (self.engineConfig.getThemeBgSceneBoxColor()) localBox.add_widget( Button(markup=True, halign="left", valign="middle", padding_x=10, font_size=15, text='[b]' + item['name'] + '[/b] [u][i]' + item['type'] + '[/i][/u]', color=self.engineConfig.getThemeTextColor(), background_normal='', background_color=currentColor, on_press=partial(self.showAssetGUI, item), size_hint=(1, None), height=90)) if item['type'] == 'ImageResource': localPrevListBox = AsyncImage(source=item['path'], size_hint=(0.4, None), height=90) with localPrevListBox.canvas.before: Color( self.engineConfig.getThemeCustomColor('background')[0], self.engineConfig.getThemeCustomColor('background')[1], self.engineConfig.getThemeCustomColor('background')[2], self.engineConfig.getThemeCustomColor('background')[3]) localPrevListBox.rect = Rectangle( size=localPrevListBox.size, pos=localPrevListBox.pos) def update_rect(instance, value): instance.rect.pos = instance.pos instance.rect.size = instance.size localPrevListBox.bind(pos=update_rect, size=update_rect) localBox.add_widget(localPrevListBox) elif item['type'] == 'FontResource': localBox.add_widget( Label(font_name=item['path'], size_hint=(0.4, None), height=90, text='Font')) elif item['type'] == 'JSONResource': localBox.add_widget( Label(size_hint=(0.4, None), height=90, text='JSON DATA')) localBox.add_widget( Button( markup=True, halign="left", valign="middle", padding_x=10, font_size=15, text='[b]Delete[/b]', color=(self.engineConfig.getThemeCustomColor("alert")), background_normal='', background_color=( self.engineConfig.getThemeCustomColor('background')), on_press=partial(self.deleteAsset, item), size_hint=(1, None), height=90)) print('ADDED ', item) alllocalBox.add_widget(localBox) self.sceneScroller.clear_widgets() self.sceneScroller.add_widget(alllocalBox)
class Item(GridLayout): def __init__(self, name, description, image_link, inventory: UserInventory, username, **kwargs): super(Item, self).__init__(**kwargs) try: os.makedirs('imgcache') except FileExistsError: Logger.warning("Image Cache Exists.") self.size_hint_y = None self.height = 50 self.cols = 3 self.inventory = inventory self.name = Label(text=name) self.name.bind(on_touch_down=self.on_item_pressed) self.add_widget(self.name) self.description = Label(text=description) self.image_link = image_link try: r = requests.get(image_link, timeout=(5, 20)) except requests.exceptions.MissingSchema: return r.raise_for_status() if r.ok: picname = os.path.basename(urllib.parse.urlparse(image_link).path) if picname is None: picname = "temp.jpg" f = open("imgcache/" + picname, mode="wb") f.write(r.content) f.close() self.image = AsyncImage(source="imgcache/" + picname, pos_hint={'left': 1}) self.image.bind(on_touch_down=self.open_image) self.owner_username = username delete_btn = Button(text="X", size_hint=[None, 1], width=60) delete_btn.bind(on_press=lambda x: self.delete_item()) self.add_widget(delete_btn) self.popup = None self.description.text_size = [ self.description.size[0] * 3, self.description.size[1] ] def clear_cache(self, instance): try: shutil.rmtree('imgcache/') os.makedirs( 'imgcache' ) #this is the exact same code used for the music cache except FileNotFoundError: #i disgust myself too. os.makedirs('imgcache') except PermissionError: Logger.warning( "Cannot clear inventory cache due to permission error.") except Exception as e: Logger.warning(traceback.format_exc()) def on_item_pressed(self, inst, touch): if self.name.collide_point(*touch.pos): self.open_popup() def get_name(self): return self.name.text def get_description(self): return self.description.text def get_image_link(self): return self.image def get_popup(self): return self.popup def set_name(self, name): self.name = name def set_description(self, description): self.description = description def set_image_link(self, image_link): self.image = image_link def open_image(self, inst, touch): if self.image.collide_point(*touch.pos): webbrowser.open(self.image_link) def delete_item(self): if self.inventory is not None: self.inventory.delete_item(self.name.text) def build_item_window(self): if self.popup is None: main_grid = GridLayout(cols=2) main_grid.add_widget(self.image) main_grid.add_widget(self.description) self.popup = Popup(title=self.name.text + " created by " + self.owner_username, content=main_grid, size_hint=(.5, .3), pos_hint={ 'left': .1, 'top': 1 }, background_color=[0, 0, 0, 0]) return self.popup def open_popup(self): try: popup = self.build_item_window() popup.bind(on_dismiss=self.clear_cache) popup.open() except AttributeError: Logger.warning(traceback.format_exc()) return # Encoded by: name#description#image_link#owner_name def encode(self): return self.name.text + '#' + self.description.text + '#' + self.image_link + '#' + self.owner_username
class Item(GridLayout): def __init__(self, name, description, image_link, inventory: UserInventory, username, **kwargs): super(Item, self).__init__(**kwargs) try: os.makedirs('imgcache') except FileExistsError: print("Image Cache Exists.") self.size_hint_y = None self.height = 50 self.cols = 3 self.inventory = inventory self.name = Label(text=name) self.name.bind(on_touch_down=self.on_item_pressed) self.add_widget(self.name) self.description = Label(text=description) self.image_link = image_link r = requests.get(image_link, timeout=(5, 20)) r.raise_for_status() if r.ok: picname = urllib.request.urlopen( urllib.request.Request(image_link, method='HEAD', headers={'User-Agent': 'Mozilla/5.0' })).info().get_filename() if picname is None: picname = "temp.jpg" f = open("imgcache/" + picname, mode="wb") f.write(r.content) f.close() self.image = AsyncImage(source="imgcache/" + picname, pos_hint={'left': 1}) self.image.bind(on_touch_down=self.open_image) self.owner_username = username delete_btn = Button(text="X", size_hint=[None, 1], width=60) delete_btn.bind(on_press=lambda x: self.delete_item()) self.add_widget(delete_btn) self.popup = None self.description.text_size = [ self.description.size[0] * 3, self.description.size[1] ] def on_item_pressed(self, inst, touch): if self.name.collide_point(*touch.pos): self.open_popup() def get_name(self): return self.name.text def get_description(self): return self.description.text def get_image_link(self): return self.image def get_popup(self): return self.popup def set_name(self, name): self.name = name def set_description(self, description): self.description = description def set_image_link(self, image_link): self.image = image_link def open_image(self, inst, touch): if self.image.collide_point(*touch.pos): webbrowser.open(self.image.source) def delete_item(self): if self.inventory is not None: self.inventory.delete_item(self.name.text) def build_item_window(self): if self.popup is None: main_grid = GridLayout(cols=2) main_grid.add_widget(self.image) main_grid.add_widget(self.description) self.popup = Popup(title=self.name.text + " created by " + self.owner_username, content=main_grid, size_hint=(.5, .3), pos_hint={ 'left': .1, 'top': 1 }, background_color=[0, 0, 0, 0]) return self.popup def open_popup(self): popup = self.build_item_window() popup.open() # Encoded by: name#description#image_link#owner_name def encode(self): return self.name.text + '#' + self.description.text + '#' + self.image_link + '#' + self.owner_username
class PhotoStrip(ScrollView): def on_press(self, filename): pass def on_release(self, filename): pass def __init__(self, *args, **kwargs): super(PhotoStrip, self).__init__(size_hint=(1, 1), pos_hint={ 'center_x': 0.5, 'center_y': 0.5 }, do_scroll_x=False, *args, **kwargs) self.register_event_type('on_press') self.register_event_type('on_release') self.strip = AsyncImage(source='photos-strip.png', allow_stretch=True, size_hint_y=1.8) self.add_widget(self.strip) self.image0 = image_button() self.image0.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image0) self.image1 = image_button() self.image1.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image1) self.image2 = image_button() self.image2.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image2) self.image3 = image_button() self.image3.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image3) self.strip.bind(size=self.update_buttons, pos=self.update_buttons) def set_path(self, path): print path path = filesystem.normpath(path) print path self.scroll_y = 1 if 'effect_y' in dir(self): # Kivy 1.6.0 doesn't have effect_y self.effect_y.value = self.effect_y.min # This is to work around a bug with the ScrollView (https://github.com/kivy/kivy/issues/2038) self.image0.source = filesystem.join(path, '0.jpg') self.image1.source = filesystem.join(path, '1.jpg') self.image2.source = filesystem.join(path, '2.jpg') self.image3.source = filesystem.join(path, 'blank') def press_btn(self, btn): self.dispatch('on_press', btn.source) def release_btn(self, btn): self.dispatch('on_release', btn.source) def update_buttons(self, instance, value): spacing = 20 padding = 25 offset = padding for img in [self.image0, self.image1, self.image2, self.image3]: img.size = (instance.norm_image_size[0] / 60) * 43, (instance.norm_image_size[1] - ((spacing * 3) + (padding * 2))) / 4 img.center_x = instance.center_x img.center_y = instance.top - ((img.height / 2) + offset) offset += img.height + spacing
def show_img(self, _type, _img_path, _chat_window_id): _chat_window = None _chat_scroll = self.ids.chat_scroll if _chat_window_id == self.member_list_current._id: _chat_window = _chat_scroll.children[0] else: _chat_window = self.chat_record.setdefault(_chat_window_id, None) if _chat_window is None: _chat_window = StackLayout(orientation='tb-lr', size_hint=[1, None]) _chat_window.width = _chat_scroll.width _chat_window.height = 0 _label_left = Label() _label_main = AsyncImage(source=_img_path, nocache=True) # _label_main.reload() _label_main.bind(on_touch_down=self.zoom_img) _label_main.size = [ _label_main.norm_image_size[0], _label_main.norm_image_size[1] ] _label_right = Label() _pos_x_hint_left = [0, 0] _pos_x_hint_main = [0, 0] _pos_x_hint_right = [0, 0] while _pos_x_hint_main[0] == 0: if _label_main.texture_size[0] >= _chat_window.width * 0.7: _pos_x_hint_main = [0.7, None] else: _pos_x_hint_main = [ _label_main.texture_size[0] / _chat_window.width, None ] if _type == 'receive': _pos_x_hint_left = [0.05, None] _pos_x_hint_right = [ 1 - _pos_x_hint_left[0] - _pos_x_hint_main[0], None ] elif _type == 'send': _pos_x_hint_left = [1 - 0.05 - _pos_x_hint_main[0], None] _pos_x_hint_right = [0.05, None] elif _type == 'time': _pos_x_hint_left = [(1 - _pos_x_hint_main[0]) / 2, None] _pos_x_hint_right = _pos_x_hint_left _chat_window.last_msg_time = time.time() _label_left.size_hint = _pos_x_hint_left _label_main.size_hint = _pos_x_hint_main _label_right.size_hint = _pos_x_hint_right _box = BoxLayout(size_hint=[1, None]) _box.height = _label_main.texture_size[1] + 30 _box.add_widget(_label_left) _box.add_widget(_label_main) _box.add_widget(_label_right) _chat_window.add_widget(_box) if _chat_window_id is None: # _chat_scroll.scroll_y = 0 self.chat_window_height = self.chat_window_height + _box.height _chat_window.height = self.chat_window_height + 30 else: _chat_window.height = _chat_window.height + _box.height self.chat_record.update({_chat_window_id: _chat_window}) pass