Esempio n. 1
0
 def showIfRightOrFalse(
         self, state):  # Setting images here for right / false state
     activeImage = []
     imgLbl = self.ids.right_false_lbl
     if state == ("Correct"):
         #imgLbl.canvas.clear()
         #self.setImgPlaceholder()
         del activeImage[0:5]
         with imgLbl.canvas.before:
             activeImage.append("src/richtigTransparent.png")
             Color(.4, .4, .4, 1)
             texture = CoreImage(
                 str(activeImage).strip("[").strip("]").strip("'")).texture
             texture.wrap = "repeat"
             Rectangle(pos=imgLbl.pos, size=imgLbl.size, texture=texture)
     elif state == ("Incorrect"):
         #imgLbl.canvas.clear()
         #self.setImgPlaceholder()
         del activeImage[0:5]
         with imgLbl.canvas.before:
             activeImage.append("src/falschTransparent.png")
             Color(.4, .4, .4, 1)
             texture = CoreImage(
                 str(activeImage).strip("[").strip("]").strip("'")).texture
             texture.wrap = "repeat"
             Rectangle(pos=imgLbl.pos, size=imgLbl.size, texture=texture)
     elif state == ("None"):
         #imgLbl.canvas.clear()
         #self.setImgPlaceholder()
         del activeImage[0:5]
Esempio n. 2
0
 def __init__(self, **kwargs):
     Logger.info('ChicagoApp init FIRED')
     super(ChicagoApp, self).__init__(**kwargs)
     ##fix for old file locations
     if platform == 'android':
         if isfile(App.get_running_app().user_data_dir +
                   '/game.dat') is False and isfile('./game.dat') is True:
             rename('./game.dat',
                    App.get_running_app().user_data_dir + '/game.dat')
         if isfile(App.get_running_app().user_data_dir +
                   '/shop.dat') is False and isfile('./shop.dat') is True:
             rename('./shop.dat',
                    App.get_running_app().user_data_dir + '/shop.dat')
     ##Cache all the card images
     for path in ('./images/PNG-cards-1.3', './images/back'):
         for f in listdir(path):
             if isfile(path + '/' + f) and f[-4:] == '.png':
                 data = io.BytesIO(open(path + '/' + f, "rb").read())
                 CoreImage(data, ext="png", filename=path + '/' + f)
     ##and the reset
     for f in ('cardborder.png', 'greenTable.jpg', 'simpleTable.jpg'):
         data = io.BytesIO(open('./images/' + f, "rb").read())
         CoreImage(data, ext=f[-3:], filename='./images/' + f)
     if platform == "android":
         ##set up AdBuddiz
         AdBuddiz.setPublisherKey("_ANDROIDADKEY_")
         #AdBuddiz.setTestModeActive() # todo - Comment this line before releasing!
         AdBuddiz.cacheAds(PythonActivity.mActivity)
     elif platform == 'ios' and paidApp is False:
         #import <AdBuddiz/AdBuddiz.h>
         Ad.setPublisherKey_("_IOSADDKEY_")
         Ad.cacheAds()
         Ad.setTestModeActive()
         pass
Esempio n. 3
0
    def on_update(self):
        if not self.value == self.pixel_slider.on_update():
            self.value = self.pixel_slider.on_update()

            # Scale value based on dominoes produced
            width_in_pixels, height_in_pixels = self.calc_width_and_height()
            self.imgSmall = self.image.resize(
                (width_in_pixels, height_in_pixels), resample=Image.BILINEAR)

            # Scale back up using NEAREST to original size
            self.pixeate_image = self.imgSmall.resize(
                self.image.size, Image.NEAREST).convert("L")

            data = BytesIO()
            self.pixeate_image.save(data, format='png')
            data.seek(0)

            # update image
            self.pixelate_rect.texture = CoreImage(BytesIO(data.read()),
                                                   ext='png').texture

            # update label
            self.label.text = "This would require " + str(
                math.ceil(width_in_pixels * height_in_pixels / 2 /
                          55)) + " sets of dominoes ( " + str(
                              width_in_pixels * height_in_pixels //
                              2) + " dominoes in total )"

        # generate domino image on button press
        if self.generate_pressed:
            # create and update domino image
            self.domino_image = calculate.generate_domino_graphics(
                (ImageOps.invert(self.imgSmall.convert('RGB'))
                 if self.color_switch.on else self.imgSmall),
                self.imgSmall.size[0], self.imgSmall.size[1], self.filename,
                self.color_switch.on)
            self.domino_image.show()
            print("GENERATION COMPLETE")

            data = BytesIO()
            # if image will be too large for kivy texture, resize the image so that it can be rendered
            if self.domino_image.size[0] * self.domino_image.size[
                    1] > 256000000:
                print("must resize image! original size was:",
                      self.domino_image.size)
                self.domino_image.resize((16000, 16000),
                                         Image.NEAREST).save(data,
                                                             format='png')
            else:
                self.domino_image.save(data, format='png')
            data.seek(0)
            self.domino_rect.texture = CoreImage(BytesIO(data.read()),
                                                 ext='png').texture

            # return generate button to former state
            self.generate_button.texture = CoreImage(
                './buttons/generate_button.png').texture
            self.generate_pressed = False
Esempio n. 4
0
    def build_canvas(self, dt):

        # get 3 textures
        curdir = dirname(__file__)
        arrow_left = CoreImage(join(curdir, 'arrow_left.png')).texture
        arrow_middle = CoreImage(join(curdir, 'arrow_middle.png')).texture
        arrow_right = CoreImage(join(curdir, 'arrow_right.png')).texture

        self.canvas.before.clear()
        with self.canvas.before:
            cmax = ((self.date_end - self.date_start) / float(self.date_step))
            x, y = self.pos
            w, h = self.size
            fh = 100
            bh = 10
            cy = y + h / 2
            h = fh * 2
            r = range(self.date_start, self.date_end, self.date_step)
            for index, cx in enumerate(r):
                alpha = (cx - self.date_start) / (float(self.date_end) -
                        float(self.date_start))
                
                # create background of arrow (part of)
                c = 0.9 - (0.4 * alpha)
                a = 1.0 - 0.4 * alpha
                Color(c, c, c, a)

                if index == 0:
                    texture = arrow_left
                    border = (2, 2, 2, 8)
                elif index == len(r) - 1:
                    texture = arrow_right
                    border = (2, 126, 2, 2)
                else:
                    texture = arrow_middle
                    border = (2, 0, 2, 0)
                BorderImage(pos=(x, cy - fh), size=(w/cmax, h), texture=texture,
                        border=border)

                # create lines
                x = int(x)
                if index > 0:
                    Color(1, 1, 1, .8)
                    Line(points=[x, cy - fh - bh, x, cy + fh + bh])

                # create label (333f43)
                label = CoreLabel(text=str(cx),
                        font_size=14, font_name='fonts/DroidSans.ttf')
                label.refresh()
                Color(0x33/255., 0x3f/255., 0x43/255.)

                # trick to invert the label orientation
                tc = label.texture.tex_coords
                th, tw = label.texture.size
                tc = tc[-2:] + tc[0:-2]
                Rectangle(pos=(x + 5, cy - th / 2), size=(tw, th),
                        texture=label.texture, tex_coords=tc)
                x += w / cmax
Esempio n. 5
0
 def slurp_file_to_image(self, filename, container_widget):
     # print("slurping {} to {}".format(filename, container_widget))
     data = io.BytesIO(open(filename, "rb").read())
     self.active_fold_thumbnail = CoreImage(io.BytesIO(
         open(filename, "rb").read()),
                                            ext="jpg").texture
     container_widget.texture = CoreImage(data, ext="jpg").texture
     # container_widget.size = container_widget.texture_size
     # print("removing thumb {}".format(filename))
     os.remove(filename)
Esempio n. 6
0
class SpaceShip(Widget):
    orientation = NumericProperty(180)
    space_game = ObjectProperty(None)
    propulsion_texture = ObjectProperty(
        CoreImage("atlas://img/space_invader/spaceEffects_005").texture)
    REACTOR_SPRITE = [
        CoreImage("atlas://img/space_invader/spaceEffects_005").texture,
        CoreImage("atlas://img/space_invader/spaceEffects_006").texture,
        CoreImage("atlas://img/space_invader/spaceEffects_007").texture,
        CoreImage("atlas://img/space_invader/spaceEffects_006").texture,
    ]
    alive = BooleanProperty(True)

    gun_cooldown_time = NumericProperty(0.1)
    gun_fire_interval = NumericProperty(2.4)

    def __init__(self, space_game, **kwargs):
        self.space_game = space_game
        self.propulsion = cycle(SpaceShip.REACTOR_SPRITE)
        self.propulsion_counter = 0
        super(SpaceShip, self).__init__(**kwargs)
        self.event = Clock.schedule_interval(self.animate_propulsion, FPS)

    def on_alive(self, instance, value):
        if not self.alive:
            if self.event is not None:
                self.event.cancel()

            if self.parent is not None:
                Animation.cancel_all(self)
                if self.boom:
                    self.boom.play()
                self.add_debris()

                self.parent.remove_widget(self)

    def add_debris(self):
        dirs = [-2, -1, 0, 1, 2]
        for _ in range(10):
            tmp_debris = Debris(
                velocity_x=choice(dirs) * 60.0,
                velocity_y=choice(dirs) * 60.0,
            )
            self.parent.add_widget(tmp_debris)
            tmp_debris.center = self.center
            tmp_debris.launch()

    def collide_ammo(self, ammo):
        raise NotImplementedError()

    def animate_propulsion(self, dt):

        self.propulsion_counter += 1
        if self.propulsion_counter % PROPULSION_FREQUENCY == 0:
            self.propulsion_texture = next(self.propulsion)
Esempio n. 7
0
 def load_texture(self, filename):
     texture = Cache.get('textures', filename)
     if texture is not None:
         return texture
     if filename == 'lwf_img_replace_character_01.png':
         texture = CoreImage(
             '../../res/characters/washed_out_cassandra/washed_out_cassandra_bustup.png'
         ).texture
     else:
         texture = CoreImage('../../res/lwf/' + filename).texture
     Cache.append('textures', filename, texture)
     return texture
Esempio n. 8
0
	def iftIter(self,a=0):
		if self.iftii >= 2:
			self.iftii = 0
		
		print("iftIter", self.iftii)
		data = BytesIO(open(self.iftI[self.iftii], "rb").read())
		im = CoreImage(data, ext="jpg", filename="image.jpg")
		#self.ift.canvas.clear()
		self.ift.imgTexture = CoreImage( im, ext='jpg', filename='yy.jpg' )
		self.iftii+=1
	
		Clock.schedule_once(self.iftIter, 1.0)
Esempio n. 9
0
    def __init__(self, filepath, **kwargs):
        super(Homepage, self).__init__(**kwargs)

        self.filepath = filepath
        self.filename = filepath.replace('.', '/').split('/')[-2]

        Window.clearcolor = (0.2, 0.2, 0.2, 1)
        self.color_switch = Switch()
        self.canvas.add(self.color_switch)

        # LEFT IMAGE #
        im = Image.open(filepath).convert("RGBA")
        self.image = im.copy()
        width, height = self.image.size
        self.w_h_ratio = width / height
        self.image_rect = Rectangle(texture=CoreImage(self.filepath).texture)
        self.canvas.add(self.image_rect)

        # CENTER PIXELATED IMAGE & SLIDER #
        self.pixeate_image = im.copy()
        self.pixelate_rect = Rectangle()
        self.canvas.add(self.pixelate_rect)
        self.value = None
        self.pixel_slider = Slider(
            1, ((Window.width - self.image_rect.size[0]) // 2,
                (Window.height - self.image_rect.size[1]) // 2),
            self.pixelate_rect.size)

        self.generate_pressed = False
        self.generate_button = Rectangle(
            texture=CoreImage('./buttons/generate_button.png').texture)
        self.canvas.add(self.generate_button)

        # RIGHT DOMINO IMAGE #
        self.domino_image = Image.new(mode='RGBA',
                                      size=(width, height),
                                      color=(235, 74, 90, 150))
        data = BytesIO()
        self.domino_image.save(data, format='png')
        data.seek(0)
        self.domino_rect = Rectangle(
            texture=CoreImage(BytesIO(data.read()), ext='png').texture)
        self.canvas.add(self.domino_rect)

        self.label = Label()
        self.add_widget(self.label)

        self.imgSmall = None

        self.on_update()
        self.on_layout((Window.width, Window.height))
Esempio n. 10
0
    def __init__(self,
                 level,
                 goal_music_seq,
                 duration,
                 edit_goal_play_status=None):
        super(LevelOptions, self).__init__()
        self.level = level  # level number
        self.audio = Audio(2)
        self.mixer = Mixer()
        self.audio.set_generator(self.mixer)

        self.options_bar = Rectangle(pos=(0, 0))
        self.home_button = Rectangle(
            texture=CoreImage('images/home.png').texture)
        self.play_button = Rectangle(
            texture=CoreImage('images/play.png').texture)
        self.reset_button = Rectangle(
            texture=CoreImage('images/reset.png').texture)
        self.check_button = Rectangle(
            texture=CoreImage('images/check.png').texture)
        self.on_layout((Window.width, Window.height))

        self.add(colors['grey'])
        self.add(self.options_bar)
        self.add(colors['green'])
        self.add(self.home_button)
        self.add(self.play_button)
        self.add(self.reset_button)
        self.add(self.check_button)

        self.is_playing = False
        self.start_time = None
        self.duration = 0
        self.goal_music_seq = None

        self.duration_circle = Line()
        self.add(self.duration_circle)

        # true iff you recently lost or won the game
        self.win_or_lose = False

        self.win_gen = WaveGenerator(WaveFile("./data/win_sound.wav"))
        self.lose_gen = WaveGenerator(WaveFile("./data/lose_sound.wav"))

        self.goal_music_seq = goal_music_seq
        self.duration = duration

        self.button_press_time = None

        self.edit_goal_play_status = edit_goal_play_status
Esempio n. 11
0
    def _load(self):
        # late import to prevent recursive import.
        global CoreImage
        if CoreImage is None:
            from kivy.core.image import Image as CoreImage

        # must be a name finished by .atlas ?
        filename = self._filename
        assert (filename.endswith('.atlas'))
        filename = filename.replace('/', os.sep)

        Logger.debug('Atlas: Load <%s>' % filename)
        with open(filename, 'r') as fd:
            meta = json.load(fd)

        Logger.debug('Atlas: Need to load %d images' % len(meta))
        d = dirname(filename)
        textures = {}
        for subfilename, ids in meta.items():
            subfilename = join(d, subfilename)
            Logger.debug('Atlas: Load <%s>' % subfilename)

            # load the image
            ci = CoreImage(subfilename)

            # for all the uid, load the image, get the region, and put
            # it in our dict.
            for meta_id, meta_coords in ids.items():
                x, y, w, h = meta_coords
                textures[meta_id] = ci.texture.get_region(*meta_coords)

        self.textures = textures
Esempio n. 12
0
 def clock_thread(self):
     while True:
         if GLO.stop.is_set():  # stop thread so that the program can quit
             return
         # get some basic settings
         config = ConfigParser.get_configparser('app')
         maxw = max(10, int(config.get('settings', 'labw')))
         maxh = max(10, int(config.get('settings', 'labh')))
         # create blank canvas
         canvas_img = pilImage.new('RGB', (maxw, maxh),
                                   color=(255, 255, 255))
         # draw text on the canvas
         if GLO.font_pool:
             self.canvas_drawtext(canvas_img, maxw, maxh, self.textbox.text)
         # clean up spaces from text input
         #self.textbox.text = re.sub(r'\s\s+', ' ', self.textbox.text.lstrip())
         # save png to disk
         #canvas_img.save('image_main.png')
         # live memory texture
         data = BytesIO()
         canvas_img.save(data, format='jpeg')
         data.seek(0)  # yes, this is also important!
         self.imbytes = data.read()
         im = CoreImage(BytesIO(self.imbytes), ext='jpeg')
         self.update_elements(
             im
         )  # instead of self.beeld.texture = im.texture, cannot update root widget from thread
         sleep(1)
Esempio n. 13
0
def openCV_to_kivy(cvImage):
    # encode the OpenCV image in PNG format
    _, imPNG = cv.imencode(".png", cvImage)
    # create a binary data stream for reading that data
    data = io.BytesIO(imPNG.tobytes())
    # create a Kivy Core Image data structure to hold that data
    return CoreImage(data, ext="png")
Esempio n. 14
0
    def texture_update(self, *largs):
        if not self.source:
            self.texture = None
        else:
            filename = resource_find(self.source)
            self._loops = 0
            if filename is None:
                return Logger.error(
                    'Image: Error reading file {filename}'.format(
                        filename=self.source))
            mipmap = self.mipmap
            if self._coreimage is not None:
                self._coreimage.unbind(on_texture=self._on_tex_change)
            try:
                if PY2 and isinstance(filename, str):
                    filename = filename.decode('utf-8')
                self._coreimage = ci = CoreImage(filename,
                                                 mipmap=mipmap,
                                                 anim_delay=self.anim_delay,
                                                 keep_data=self.keep_data,
                                                 nocache=self.nocache)
            except:
                Logger.error('Image: Error loading texture {filename}'.format(
                    filename=self.source))
                self._coreimage = ci = None

            if ci:
                ci.bind(on_texture=self._on_tex_change)
                self.texture = ci.texture
Esempio n. 15
0
    def _load_tile(self, tile):
        # global db context cannot be shared across threads.
        ctx = threading.local()
        if not hasattr(ctx, "db"):
            ctx.db = sqlite3.connect(self.filename)

        # get the right tile
        c = ctx.db.cursor()
        c.execute(
            ("SELECT tile_data FROM tiles WHERE "
            "zoom_level=? AND tile_column=? AND tile_row=?"),
            (tile.zoom, tile.tile_x, tile.tile_y))
        # print "fetch", tile.zoom, tile.tile_x, tile.tile_y
        row = c.fetchone()
        if not row:
            tile.state = "done"
            return

        # no-file loading
        try:
            data = io.BytesIO(row[0])
        except:
            # android issue, "buffer" does not have the buffer interface
            # ie row[0] buffer is not compatible with BytesIO on Android??
            data = io.BytesIO(bytes(row[0]))
        im = CoreImage(data, ext='png',
                filename="{}.{}.{}.png".format(tile.zoom, tile.tile_x,
                    tile.tile_y))

        if im is None:
            tile.state = "done"
            return

        return self._load_tile_done, (tile, im, )
Esempio n. 16
0
def get_module_resource_path(file_name, size, resource_package=__name__):
    import os
    regex = re.compile(
        r'^(?:http|ftp)s?://'  # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'  # domain...
        r'localhost|'  # localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'  # ...or ip
        r'(?::\d+)?'  # optional port
        r'(?:/?|[/?]\S+)$',
        re.IGNORECASE)

    if regex.match(file_name) or os.path.isfile(file_name):
        image = Image(source=file_name)
    else:
        __requires__ = ["CherryPy < 3"
                        ]  # Must be set before pkg_resources import
        import pkg_resources
        resource_path = '/' + file_name

        reader = pkg_resources.resource_stream(resource_package, resource_path)
        if reader:
            stream = io.BytesIO(reader.read())
        _, file_extension = os.path.splitext(file_name)

        im = CoreImage(stream, ext=file_extension[1:])

        image = Image(source="")
        image.texture = im.texture
        image.reload()
        image.size = size
    return image
Esempio n. 17
0
 def on_collision_source(self, instance, value):
     if value is None:
         return
     try:
         self.__collision_mask = CoreImage(value, keep_data=True)
     except:
         self.__collision_mask = None
Esempio n. 18
0
    def make_profile_img(self,
                         width,
                         do_crop=True,
                         circ_img=None,
                         bw=False,
                         circularize=True):
        img_src = os.path.join(PATH_AVATARS, f'{self.app.username}.png')
        if not os.path.exists(img_src):
            img_src = os.path.join(PATH_GUI_ASSETS, 'avatars',
                                   f'{self.app.username}.png')
        if not os.path.exists(img_src):
            img_src = PATH_DEFAULT_AVATAR

        circ_img = circularize_img(img_src,
                                   width,
                                   do_crop=do_crop,
                                   bw=bw,
                                   circularize=circularize)
        avatar_layout = LayoutAvatar()
        byte = io.BytesIO(circ_img.read())

        img = CoreImage(byte, ext='png')
        avatar = ProfileAvatar()
        avatar.texture = img.texture
        avatar_layout.height = dp(width)
        avatar_layout.width = dp(width)
        avatar_layout.add_widget(avatar)
        return (circ_img, byte, avatar, avatar_layout)
Esempio n. 19
0
 def init(self):
     self.step = 1 / 60.
     ci = CoreImage("pymunk_logo.png", keep_data=True)
     self.logo_lines = self.create_logo_lines(ci)
     self.logo_img = ci
     self.touches = {}
     self.start()
Esempio n. 20
0
    def exibir_imagem(self):
        ce = self.ids.conteudo_edicao
        ce.clear_widgets()

        #############################
        # Obtendo Textura da Imagem #
        #############################

        # Criando Buffer
        image_bytes = io.BytesIO()

        # Salvando Imagem de PIL no Buffer
        ed.img.save(image_bytes, format=ed.img_formato)

        # Defininto ponto inicial 0
        image_bytes.seek(0)

        # Carregando imagem no CoreImage -> Ex: (Buffer, ext='png')
        im = CoreImage(image_bytes, ext=ed.img_formato)

        # Coletando textura da Imagem de CoreImage
        tex = im.texture

        # Encerrando Buffer
        image_bytes.close()

        # ----------------------- #

        # Criando Widget de Imagem
        img = Image(nocache=True)
        # Passando a textura gerada no CoreImage para ele
        img.texture = tex

        ce.add_widget(img)
Esempio n. 21
0
    def __init__(self, **kwargs):
        super(SadpandaRoot, self).__init__(**kwargs)
        # list of previous screens
        self.screen_list = []
        Loader.loading_image = CoreImage("img/loading.gif", size=(16, 16))

        Clock.schedule_once(self.start_thread)
Esempio n. 22
0
 def setImage(self, image):
     self.source = image
     self.texture = CoreImage(self.source).texture
     self.rect = Rect(self.rect.x, self.rect.y, self.texture.width,
                      self.texture.height)
     self.width = self.texture.width
     self.height = self.texture.height
Esempio n. 23
0
    def build(self):
        layout = BoxLayout()
        layout01 = BoxLayout(orientation='vertical', size_hint_x=0.3)
        layout01.add_widget(start_btn)
        layout01.add_widget(pause_btn)
        pause_btn.disabled = True
        layout01.add_widget(stop_btn)
        stop_btn.disabled = True
        #		layout01.add_widget(self.e1)
        #		layout01.add_widget(self.l1)
        layout01.add_widget(exit_btn)
        layout.add_widget(layout01)

        layout02 = BoxLayout(orientation='vertical')
        img = np.full((1, 1, 3), 0, np.uint8)  # placeholder
        imgIO = BytesIO()
        qr = Image.fromarray(img)
        qr.save(imgIO, format='png')
        imgIO.seek(0)
        imgData = BytesIO(imgIO.read())
        with kvbox.canvas:
            image = kiImage(source='', pos=kvbox.pos, size=kvbox.size)
            image.texture = CoreImage(imgData, ext='png').texture
        layout02.add_widget(kvbox)
        layout.add_widget(layout02)
        return layout
Esempio n. 24
0
    def _read_stream(self):
        try:
            stream = urllib.request.urlopen(self.url)
        except Exception as err:
            self.quit = True
            Logger.error(
                "MjpegViewer: Failed to open url: {} - error: {}".format(
                    self.url, err))
            return None

        bytes = b''
        while not self.quit:
            try:
                # read in stream until we get the entire snapshot
                bytes += stream.read(1024)
                a = bytes.find(b'\xff\xd8')
                b = bytes.find(b'\xff\xd9')
                if a != -1 and b != -1:
                    jpg = bytes[a:b + 2]
                    bytes = bytes[b + 2:]

                    data = io.BytesIO(jpg)
                    im = CoreImage(data, ext="jpeg", nocache=True)
                    return im

            except Exception as err:
                Logger.error(
                    "MjpegViewer: Failed to read_queue url: {} - error: {}".
                    format(self.url, err))
                return None
Esempio n. 25
0
    def itemProfile(self):
        """
        :return: Get all information of the item
        """
        # return image, title, priceType, saleStatus, postTime
        # need for view item action

        qry = "SELECT image, title, description, priceType,likeness,dislike,saleStatus, approvalStatus FROM ItemInfo WHERE itemID = %s;" % self.itemID
        self.cursor.execute(qry)
        profile = self.cursor.fetchone()

        self.title, self.descrpition, self.priceType = profile[1], profile[
            2], profile[3]
        self.likeness, self.dislike = profile[4], profile[5]
        self.saleStatus, self.approvalStatus = profile[6], profile[7]
        self.image = CoreImage(BytesIO(profile[0]), ext="png").texture

        qry = "SELECT ownerID from ItemOwner WHERE itemID = %s;" % self.itemID
        self.cursor.execute(qry)
        self.owner = self.cursor.fetchone()[0]

        qry = "SELECT frequency from ItemView WHERE itemID = %s;" % self.itemID
        self.cursor.execute(qry)
        self.views = self.cursor.fetchone()[0]

        self.rating = 0

        if self.priceType:  # for bidding
            self.getBiddingInfo()
            self.getBiddings()
        else:  # for fixed
            self.getFixedinfo()
            self.getRating()
Esempio n. 26
0
    def show_note(self, item_id):
        self.note_content = self.get_note_data(item_id)
        self.main.actionbar_widget_controller.set_title(self.note_content[3])
        texts = self.note_content[7:12]
        images = self.note_content[12:17]
        results = self.note_content[17:22]

        for i in range(5):
            if texts[i]:
                label = NoteLabel(text=texts[i])
                self.note_layout_widgets.append(label)
                self.note_layout.add_widget(label)

            if images[i]:
                pic = io.BytesIO(images[i])
                im = CoreImage(pic, ext="jpeg")
                image = NoteImage()
                image.texture = im.texture
                self.note_layout_widgets.append(image)
                self.note_layout.add_widget(image)

            if results[i]:
                label = NoteResult(text=results[i])
                self.note_layout_widgets.append(label)
                self.note_layout.add_widget(label)
Esempio n. 27
0
 def texture_update(self, *largs):
     if not self.source:
         self._clear_core_image()
         return
     source = resource_find(self.source)
     if not source:
         Logger.error('Image: Not found <%s>' % self.source)
         self._clear_core_image()
         return
     if self._coreimage:
         self._coreimage.unbind(on_texture=self._on_tex_change)
     try:
         self._coreimage = image = CoreImage(
             source,
             mipmap=self.mipmap,
             anim_delay=self.anim_delay,
             keep_data=self.keep_data,
             nocache=self.nocache
         )
     except Exception:
         Logger.error('Image: Error loading <%s>' % self.source)
         self._clear_core_image()
         image = self._coreimage
     if image:
         image.bind(on_texture=self._on_tex_change)
         self.texture = image.texture
Esempio n. 28
0
    def edit_screen(self, title, texts, images, results):
        self.reset_counters()
        self.main.container.ids.add_note_screen.ids.submit_button.text = Text.data[
            'update']

        for i in range(5):
            if texts[i]:
                widget = TextInput(text=f'{texts[i]}',
                                   size_hint=(0.95, None),
                                   height=200)
                self.text_inputs.append(widget)
                self.note_body_layout.add_widget(widget)
                self.common(Const.TEXT, widget, 0)
                self.text_counter += 1

            if images[i]:
                data = io.BytesIO(images[i])
                data.seek(0)
                im = CoreImage(io.BytesIO(data.read()), ext="jpeg")
                image = NoteImage(im=data.getvalue())
                image.texture = im.texture
                self.images.append(image)
                self.note_body_layout.add_widget(image)
                self.common(Const.IMAGE, image, 1)
                self.image_counter += 1

            if results[i]:
                widget = TextInput(text=f'{results[i]}',
                                   size_hint=(0.95, None),
                                   height=200)
                self.results.append(widget)
                self.note_body_layout.add_widget(widget)
                self.common(Const.RESULT, widget, 0)
                self.result_counter += 1
Esempio n. 29
0
    def _load(self):
        # must be a name finished by .atlas ?
        filename = self._filename
        assert(filename.endswith('.atlas'))
        filename = filename.replace('/', os.sep)

        Logger.debug('Atlas: Load <%s>' % filename)
        with open(filename, 'r') as fd:
            meta = json.load(fd)

        Logger.debug('Atlas: Need to load %d images' % len(meta))
        d = dirname(filename)
        textures = {}
        for subfilename, ids in meta.items():
            subfilename = join(d, subfilename)
            Logger.debug('Atlas: Load <%s>' % subfilename)

            # load the image
            ci = CoreImage(subfilename)

            # <RJ> this is the fix for pixel art
            ci.texture.mag_filter = 'nearest'

            # for all the uid, load the image, get the region, and put
            # it in our dict.
            for meta_id, meta_coords in ids.items():
                x, y, w, h = meta_coords
                textures[meta_id] = ci.texture.get_region(*meta_coords)

        self.textures = textures
Esempio n. 30
0
    def _update_frame(self, _):
        """
        Update the image to the new frame
        """
        try:
            # Try to receive a frame
            frame_message = self.connection.socket.recv(block=False)
            # If you did not receive a frame do not update the screen
            if frame_message is None:
                return
            logging.debug(f"FRAME:Received frame with "
                          f"length: {len(frame_message.content)}")
            self.connection.socket.send(
                Message(MESSAGE_TYPES["controller"], "Message received"))

            frame_data = io.BytesIO(frame_message.content)
            frame_data.seek(0)

            logging.debug("FRAME:Creating core image")
            self.texture = CoreImage(frame_data, ext=self.image_format).texture
            logging.debug("FRAME:Reloading screen")
            self.reload()
            logging.debug("FRAME:SCREEN UPDATED")
        except Exception as e:  # TODO: dont be broad
            print(e)
            self.stop()
            logging.error("FRAME:An error occurred", exc_info=True)
            return