예제 #1
0
    def __init__(self, **kwargs):

        # self.canvas = RenderContext(compute_normal_mat=True)
        # self.canvas.shader.source = resource_find('simple.glsl')
        self.canvas = Canvas()
        self.scene = ObjFileLoader(resource_find("testnurbs.obj"))

        self.meshes = []

        with self.canvas:
            self.fbo = Fbo(
                size=self.size, with_depthbuffer=True, compute_normal_mat=True, clear_color=(0.0, 0.0, 0.0, 0.0)
            )
            self.viewport = Rectangle(size=self.size, pos=self.pos)
        self.fbo.shader.source = resource_find("simple.glsl")
        # self.texture = self.fbo.texture

        super(Renderer, self).__init__(**kwargs)

        with self.fbo:
            # ClearBuffers(clear_depth=True)

            self.cb = Callback(self.setup_gl_context)
            PushMatrix()
            self.setup_scene()
            PopMatrix()
            self.cb = Callback(self.reset_gl_context)

        Clock.schedule_interval(self.update_scene, 1 / 60.0)

        self._touches = []
예제 #2
0
파일: __init__.py 프로젝트: pylover/kivy
    def resolve_font_name(self):
        options = self.options
        fontname = options['font_name']
        fonts = self._fonts
        fontscache = self._fonts_cache

        # is the font registered?
        if fontname in fonts:
            # return the preferred font for the current bold/italic combination
            italic = int(options['italic'])
            if options['bold']:
                bold = FONT_BOLD
            else:
                bold = FONT_REGULAR

            options['font_name_r'] = fonts[fontname][italic | bold]

        elif fontname in fontscache:
            options['font_name_r'] = fontscache[fontname]
        else:
            filename = resource_find(fontname)
            if not filename and not fontname.endswith('.ttf'):
                fontname = '{}.ttf'.format(fontname)
                filename = resource_find(fontname)

            if filename is None:
                # XXX for compatibility, check directly in the data dir
                filename = os.path.join(kivy_data_dir, fontname)
                if not os.path.exists(filename):
                    raise IOError('Label: File %r not found' % fontname)
            fontscache[fontname] = filename
            options['font_name_r'] = filename
예제 #3
0
파일: main.py 프로젝트: fresk/shs
    def setup_scene(self):
        self.scene = App.get_running_app().map_model
        normal_txt = resource_find('apps/population/map/iowa_tex.png')
        map_txt = resource_find(self.map_texture)

        Translate(0,-.12,-2)

        self.rot = Rotate(0, 0,1,0) # tilt
        Rotate(-0, 0,1,0) # tilt
        self.roty = Rotate(0,1,0,0)
        Rotate(-30, 1,0,0) # tilt
        Scale(1.8)
        Translate(0,.25, 0.05)
        self.meshes = {}
        self.mesh_transforms = {}
        self.mesh_colors = {}
        self.start_t = {}
        Color(1,1,1,1)
        for name, mesh in self.scene.objects.iteritems():
            self.tex_binding_1 = BindTexture(source=self.map_texture, index=1)
            self.render_ctx['texture1'] = 1

            PushMatrix()
            self.start_t[name] = 1.0# random.random()
            self.mesh_colors[name] = Color(1,1,1,1)
            self.mesh_transforms[name] = MatrixInstruction()
            self.meshes[name] = Mesh(
                vertices=mesh.vertices,
                indices=mesh.indices,
                fmt = mesh.vertex_format,
                mode = 'triangles',
                source = normal_txt
            )
            Color(1,1,1,1)
            PopMatrix()
예제 #4
0
파일: __init__.py 프로젝트: ali65/kivy
    def resolve_font_name(self):
        options = self.options
        fontname = options["font_name"]
        fonts = self._fonts
        fontscache = self._fonts_cache

        # is the font is registered ?
        if fontname in fonts:
            # return the prefered font for the current bold/italic combinaison
            italic = int(options["italic"])
            if options["bold"]:
                bold = FONT_BOLD
            else:
                bold = FONT_REGULAR

            options["font_name_r"] = fonts[fontname][italic | bold]

        elif fontname in fontscache:
            options["font_name_r"] = fontscache[fontname]
        else:
            filename = resource_find(fontname)
            if not filename:
                fontname = fontname + ("" if fontname.endswith(".ttf") else ".ttf")
                filename = resource_find(fontname)

            if filename is None:
                # XXX for compatibility, check directly in the data dir
                filename = os.path.join(kivy_data_dir, fontname)
                if not os.path.exists(filename):
                    raise IOError("Label: File %r not found" % fontname)
            fontscache[fontname] = filename
            options["font_name_r"] = filename
    def add_screen(self, screen):
        self.screen_in.pos = self.screen_out.pos
        self.screen_in.size = self.screen_out.size
        self.manager.real_remove_widget(self.screen_out)

        self.fbo_in = self.make_screen_fbo(self.screen_in)
        self.fbo_out = self.make_screen_fbo(self.screen_out)
        self.manager.canvas.add(self.fbo_in)
        self.manager.canvas.add(self.fbo_out)

        self.canvas = Canvas()
        self.c_front = RenderContext()
        self.c_front.shader.source = resource_find('front.glsl')
        self.c_back = RenderContext()
        self.c_back.shader.source = resource_find('back.glsl')
        self.c_backshadow = RenderContext()
        self.c_backshadow.shader.source = resource_find('backshadow.glsl')
        self.canvas.add(self.c_front)
        self.canvas.add(self.c_back)
        self.canvas.add(self.c_backshadow)

        with self.canvas.before:
            Color(1, 1, 1)
            Rectangle(
                size=self.fbo_in.size,
                texture=self.fbo_in.texture)
            Callback(self._enter_3d)
        self._build_mesh(self.fbo_in.size)
        with self.canvas.after:
            Callback(self._leave_3d)

        self.manager.canvas.add(self.canvas)
예제 #6
0
파일: app.py 프로젝트: jesseanderson/kivy
 def get_application_icon(self):
     """Return the icon of the application.
     """
     if not resource_find(self.icon):
         return ""
     else:
         return resource_find(self.icon)
예제 #7
0
파일: main.py 프로젝트: fresk/shs
    def __init__(self, **kwargs):
        _vs = kwargs.pop('vs', "")
        _fs = kwargs.pop('fs', "")

        self.canvas = Canvas()
        with self.canvas:
            fbo_size = self.width*2, self.height*2
            self.fbo = Fbo(size=fbo_size, with_depthbuffer=True, do_clear=True)
            self.fbo_color = Color(1, 1, 1, 1)
            self.fbo_rect = Rectangle()

        with self.fbo:
            self.cb = Callback(self.setup_gl_context)
            self.render_ctx = RenderContext(with_normal_mat=True)
            self.cb2 = Callback(self.reset_gl_context)

        with self.render_ctx:
            PushMatrix()
            self.setup_scene()
            PopMatrix();


        # wait that all the instructions are in the canvas to set texture
        self.texture = self.fbo.texture
        super(Renderer, self).__init__(**kwargs)

        #must be set in right order on some gpu, or fs will fail linking
        self.vs = open(resource_find("data/shaders/map.vs")).read()
        self.fs = open(resource_find("data/shaders/map.fs")).read()
        self.population_data = json.load(open(resource_find('data/county_population.json'), 'r'))
        self.calulcate_population_bounds()
        Clock.schedule_interval(self.update_glsl, 1 / 60.)
예제 #8
0
파일: mapview.py 프로젝트: fresk/shs
    def __init__(self, **kwargs):
        self.aspect = 1.0
        self.app = App.get_running_app()
        self.map_model = self.app.map_model
        self.counties = self.app.counties
        self.setup()

        self.canvas = Canvas()
        with self.canvas:
            fbo_size = self.width, self.height
            self.fbo = Fbo(size=fbo_size, with_depthbuffer=True, do_clear=True)
            self.fbo_color = Color(1, 1, 1, 1)
            self.fbo_rect = Rectangle()
        with self.fbo:
            self.cb = Callback(self.setup_gl_context)
            self.render_ctx = RenderContext(with_normal_mat=True)
            self.cb2 = Callback(self.reset_gl_context)
        self.init_scene()
        with self.render_ctx:
            PushMatrix()
            self.render_canvas = Canvas()
            PopMatrix();
        with self.render_canvas:
            self.render_scene()


        self.texture = self.fbo.texture
        super(MapView, self).__init__(**kwargs)

        #must be set in right order on some gpu, or fs will fail linking
        self.render_ctx.shader.vs = open(resource_find("data/shaders/map.vs")).read()
        self.render_ctx.shader.fs = open(resource_find('data/shaders/map.fs')).read()
        Clock.schedule_interval(self.update_glsl, 1 / 60.)
예제 #9
0
파일: app.py 프로젝트: AndiEcker/kivy
 def get_application_icon(self):
     '''Return the icon of the application.
     '''
     if not resource_find(self.icon):
         return ''
     else:
         return resource_find(self.icon)
예제 #10
0
    def _setup_object(self):

        self.clear_widgets()
        if is_ios():  # TODO enable this when iOS bug is resolved
            return

        shader_file = resource_find(os.path.join('resource', 'models', 'shaders.glsl'))
        obj_path = resource_find(self.model_path)

        self.renderer = Renderer(shader_file=shader_file)
        scene = Scene()
        camera = PerspectiveCamera(15, 1, 1, 1000)
        loader = OBJLoader()
        obj = loader.load(obj_path)

        scene.add(*obj.children)
        for obj in scene.children:
            obj.pos.x = self.position_x
            obj.pos.y = self.position_y
            obj.pos.z = self.position_z
            obj.rotation.x = self.rotation_x
            obj.rotation.y = self.rotation_y
            obj.rotation.z = self.rotation_z
            obj.material.specular = .85, .85, .85
            obj.material.color = 1.0, 1.0, 1.0
            obj.material.diffuse = 0.5, 0.5, 0.5
            obj.material.transparency = 1.0
            obj.material.intensity = 0.5
            self.imu_obj = obj
            # obj.material.shininess = 1.0

        self.renderer.render(scene, camera)
        self.renderer.bind(size=self._adjust_aspect)
        Clock.schedule_once(lambda dt: self.add_widget(self.renderer))
예제 #11
0
파일: imagebutton.py 프로젝트: fresk/shs
 def on_source(self, *args):
     v = self.source.split(".")
     source_down = ''.join(v[:-1])+"_down"+v[-1]
     self._fname_normal = resource_find(self.source)
     self._fname_down = resource_find(source_down) or self._fname_normal
     self.image_size = CoreImage.load(self._fname_normal).size
     self.background_normal = self._fname_normal
     self.background_down = self._fname_down
예제 #12
0
파일: app.py 프로젝트: DigitalCoder/kivy
    def load_kv(self, filename=None):
        '''This method is invoked the first time the app is being run if no
        widget tree has been constructed before for this app.
        This method then looks for a matching kv file in the same directory as
        the file that contains the application class.

        For example, say you have a file named main.py that contains::

            class ShowcaseApp(App):
                pass

        This method will search for a file named `showcase.kv` in
        the directory that contains main.py. The name of the kv file has to be
        the lowercase name of the class, without the 'App' postfix at the end
        if it exists.

        You can define rules and a root widget in your kv file::

            <ClassName>: # this is a rule
                ...

            ClassName: # this is a root widget
                ...

        There must be only one root widget. See the :doc:`api-kivy.lang`
        documentation for more information on how to create kv files. If your
        kv file contains a root widget, it will be used as self.root, the root
        widget for the application.
        '''
        # Detect filename automatically if it was not specified.
        if filename:
            filename = resource_find(filename)
        else:
            try:
                default_kv_directory = dirname(getfile(self.__class__))
                if default_kv_directory == '':
                    default_kv_directory = '.'
            except TypeError:
                # if it's a builtin module.. use the current dir.
                default_kv_directory = '.'

            kv_directory = self.kv_directory or default_kv_directory
            clsname = self.__class__.__name__.lower()
            if (clsname.endswith('app') and
                    not isfile(join(kv_directory, '%s.kv' % clsname))):
                clsname = clsname[:-3]
            filename = join(kv_directory, '%s.kv' % clsname)

        # Load KV file
        Logger.debug('App: Loading kv <{0}>'.format(filename))
        rfilename = resource_find(filename)
        if rfilename is None or not exists(rfilename):
            Logger.debug('App: kv <%s> not found' % filename)
            return False
        root = Builder.load_file(rfilename)
        if root:
            self.root = root
        return True
예제 #13
0
파일: _joystick.py 프로젝트: 2xR/legacy
 def build_layout(self):
     self.bg = Image(source=resource_find("joystick_bg.png"),
                     keep_ratio=False, allow_stretch=True)
     self.stick = Image(source=resource_find("joystick_fg.png"),
                        keep_ratio=False, allow_stretch=True)
     self.add_widget(self.bg)
     self.add_widget(self.stick)
     Link(self.bg, size=self, align_xy=self)
     Link(self.stick, size=(0.5, self))
     self.bind(pos=self.reposition_stick, size=self.reposition_stick)
예제 #14
0
    def __init__(self, client, **kwargs):
        self.canvas = RenderContext(use_parent_projection=True)
        self.client = client

        super(Section, self).__init__(**kwargs)
        
        self.canvas.shader.fs = open(resource_find('shaders/section_fragment.glsl')).read()
        self.canvas.shader.vs = open(resource_find('shaders/section_vertex.glsl')).read()
        
        self.recalc()
예제 #15
0
	def __init__(self, **kwargs):
		super(Knobs3D, self).__init__(**kwargs)
		with self.canvas:
			self.fbo = Fbo(with_depthbuffer = True,compute_normal_mat=True,size = Window.size)
			Rectangle(size=Window.size, texture=self.fbo.texture)
		self.fbo.add_reload_observer(self.test)
		self.fbo.shader.source = resource_find('simple.glsl')
		#self.canvas = RenderContext(compute_normal_mat=True)
		#self.canvas.shader.source = resource_find('simple.glsl')
		self.scene = ObjFile(resource_find("obj/knobs3D.obj"))
예제 #16
0
파일: main.py 프로젝트: matham/go_nogo
    def start_stage(self, restart=False):
        '''Called to start the experiment. If restart is True, it'll try to
        recover the experiment using :attr:`recovery_file`.

        It creates and starts the :class:`RootStage`.
        '''
        self.exception_value = ''
        try:
            self.barst_stage = None
            self.app_state = 'running'
            root = self.base_stage
            self.base_stage = None
            if root is not None:
                def clear_name(stage):
                    stage.name = ''
                    for child in stage.stages:
                        clear_name(child)
                clear_name(root)

            parser = self.dev_configparser
            config_path = resources.resource_find('config.ini')
            if parser is None:
                parser = self.dev_configparser = \
                    ConfigParser(name=device_config_name)
            if not config_path:
                config_path = join(self.data_directory, 'config.ini')
                with open(config_path, 'w'):
                    pass
            parser.read(config_path)
            parser.write()

            parser = self.experiment_configparser
            config_path = resources.resource_find(self.exp_config_path)
            if parser is None:
                parser = self.experiment_configparser = \
                    ConfigParser(name=exp_config_name)
            if not config_path:
                self.exp_config_path = config_path = join(self.data_directory,
                                                          'experiment.ini')
                with open(config_path, 'w'):
                    pass
            parser.read(config_path)
            parser.write()

            root = self.base_stage = RootStage()
        except Exception as e:
            self.exception_value = '{}\n\n\n{}'.format(e,
                                                       traceback.format_exc())
            logging.exception(self.exception_value)
            self.app_state = 'clear'
            return

        if restart and isfile(self.recovery_file):
            self.recover_state(self.recovery_file, stage=root)
        root.step_stage()
예제 #17
0
    def __init__(self, **kwargs):
        self.canvas = RenderContext()
        self._tpath = resource_find('mini-diffuse.png')
        self.canvas.shader.source = resource_find('simple.glsl')

        super(Renderer, self).__init__(**kwargs)
        with self.canvas:
            PushMatrix()
            self.setup_scene()
            PopMatrix()
        Clock.schedule_interval(self.update_glsl, 1 / 60.)
예제 #18
0
파일: main.py 프로젝트: 4johndoe/kivy
 def __init__(self, **kwargs):
     self.canvas = RenderContext(compute_normal_mat=True)
     self.canvas.shader.source = resource_find('simple.glsl')
     self.scene = ObjFile(resource_find("monkey.obj"))
     super(Renderer, self).__init__(**kwargs)
     with self.canvas:
         self.cb = Callback(self.setup_gl_context)
         PushMatrix()
         self.setup_scene()
         PopMatrix()
         self.cb = Callback(self.reset_gl_context)
     Clock.schedule_interval(self.update_glsl, 1 / 60.)
예제 #19
0
    def draw_keys(self):
        layout = self.available_layouts[self.layout]
        layout_rows = layout['rows']
        layout_geometry = self.layout_geometry
        layout_mode = self.layout_mode

        # draw background
        w, h = self.size

        background = resource_find(self.background)
        texture = Image(background, mipmap=True).texture
        self.background_key_layer.clear()
        with self.background_key_layer:
            Color(*self.background_color)
            BorderImage(texture=texture, size=self.size,
                    border=self.background_border)

        # XXX seperate drawing the keys and the fonts to avoid
        # XXX reloading the texture each time

        # first draw keys without the font
        key_normal = resource_find(self.key_background_normal)
        texture = Image(key_normal, mipmap=True).texture
        with self.background_key_layer:
            for line_nb in range(1, layout_rows + 1):
                for pos, size in layout_geometry['LINE_%d' % line_nb]:
                        BorderImage(texture=texture, pos=pos, size=size,
                                border=self.key_border)

        self.labels = []
        font_size = int(w) / 60
        key_nb = 0
        for pos, size in layout_geometry['LINE_1']:
            # retrieve the relative text
            text = layout[layout_mode + '_1'][key_nb][0]
            l = Label(text=text, font_size=font_size, pos=pos, size=size,
                    font_name=self.font_name)
            self.add_widget(l)
            self.labels.append(l)
            key_nb += 1
        # then draw the text
        # calculate font_size
        font_size = int(w) / 46
        # draw
        for line_nb in range(2, layout_rows + 1):
            key_nb = 0
            for pos, size in layout_geometry['LINE_%d' % line_nb]:
                # retrieve the relative text
                text = layout[layout_mode + '_' + str(line_nb)][key_nb][0]
                l = Label(text=text, font_size=font_size, pos=pos, size=size,
                        font_name=self.font_name)
                self.add_widget(l)
                key_nb += 1
예제 #20
0
    def __init__(self, **kwargs):
        super(PageCurl, self).__init__(**kwargs)
        self.c_front = RenderContext()
        self.c_front.shader.source = resource_find('front.glsl')
        self.c_back = RenderContext()
        self.c_back.shader.source = resource_find('back.glsl')
        self.c_backshadow = RenderContext()
        self.c_backshadow.shader.source = resource_find('backshadow.glsl')

        self.canvas.add(self.c_front)
        self.canvas.add(self.c_back)
        self.canvas.add(self.c_backshadow)

        self.texture = CoreImage(self.source).texture
        Clock.schedule_interval(self.update_glsl, 1 / 60.)
예제 #21
0
파일: main.py 프로젝트: brianhou/GPIS
 def __init__(self, grasp, **kwargs):
     self.grasp = grasp
     self.canvas = RenderContext(compute_normasl_mat=True)
     self.canvas.shader.source = resource_find('simple.glsl')
     self.scene = ObjFile(resource_find(self.grasp.obj_file))
     #self.scene = ObjFile(resource_find('Co_clean.obj'))
     super(Renderer, self).__init__(**kwargs)
     with self.canvas:
         self.cb = Callback(self.setup_gl_context)
         PushMatrix()
         self.setup_scene()
         PopMatrix()
         self.cb = Callback(self.reset_gl_context)
     Clock.schedule_once(self.rot_up)
     Clock.schedule_once(self.rot_left)
예제 #22
0
    def __init__(self, **kwargs):

        # self.canvas=InstructionGroup()
        self.canvas = RenderContext(compute_normal_mat=True)
        self.canvas.shader.source = resource_find("simple.glsl")
        print sys.argv[1]
        self.scene = ObjFile(resource_find(sys.argv[1]))
        # print self.scene.mtl
        super(meshv, self).__init__(**kwargs)

        # self.add_widget(Sprite(
        #    size=(200,200),
        #    center=(1000,200)
        # ))
        global texture_id_
        texture_id_ = {}
        global global_texture_filename
        global_texture_filename = "checkerboard.jpg"
        global global_uv_filename
        global_uv_filename = "checkerboard.jpg"

        for id in range(0, len(self.scene.objects)):
            shutil.copyfile(
                os.path.split(sys.argv[1])[0] + "/texture/" + self.scene.material.values()[id] + ".png",
                os.path.split(sys.argv[1])[0] + "/texture/tmp_" + self.scene.material.values()[id] + ".png",
            )

        self.checkerboard_statue = 0

        with self.canvas:
            self.cb = Callback(self.setup_gl_context)
            PushMatrix()
            self.setup_scene()
            PopMatrix()
            # Color(0, 1, 1, 0.6)
            # self.rect = Rectangle(size=self.size,pos=self.pos)
            self.cb = Callback(self.reset_gl_context)

        self.camera_loc = [0, 1, 0]
        self.camera_up = [0, 0, 1]
        self.camera_r = 2
        Clock.schedule_once(self.update_glsl, 1 / 60.0)

        self._touches = []
        self.texture_id = 0
        # self.btn_next_texture()
        self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
        self._keyboard.bind(on_key_down=self._on_keyboard_down)
예제 #23
0
    def draw_object(self, obj_id):
        m = self._scene.objects[obj_id]
        self.obj_rot_x = Rotate(self.obj_rotation[0], 1, 0, 0)
        self.obj_rot_y = Rotate(self.obj_rotation[1], 0, 1, 0)
        self.obj_rot_z = Rotate(self.obj_rotation[2], 0, 0, 1)
        self.obj_translate = Translate(xyz=self.obj_translation)

        if len(m.indices) > 2 ** 16:
            print('%s too big! %s indices' % (obj_id, len(m.indices)))

        if m.texture:
            print("loading texture %s " % m.texture)
            img = Image(source=resource_find(
                join(dirname(self.scene), m.texture)))
            texture = img.texture
            if texture:
                texture.wrap = 'repeat'
        else:
            texture = None

        vertex_lenght = sum(x[1] for x in m.vertex_format)
        if len(m.vertices) % vertex_lenght:
            print((
                (
                    'warning: vertices lenght (%s)'
                    'is not a multiple of vertex_format lenght(%s)'
                )
                % (len(m.vertices), vertex_lenght)))
        Mesh(
            vertices=m.vertices,
            indices=m.indices,
            fmt=m.vertex_format,
            texture=texture,
            mode=self.mode)
예제 #24
0
    def create_motion_blur(self):
        self.motion_blur_fbo = Fbo(size=PICKING_BUFFER_SIZE,
                                   with_depthbuffer=True,
                                   compute_normal_mat=True,
                                   clear_color=(1.0, 1.0, 1.0, 0.0))

        self.motion_blur_fbo.shader.source = resource_find('./kivy3dgui/gles2.0/shaders/dop.glsl')
예제 #25
0
파일: image.py 프로젝트: kivy/kivy
    def texture_update(self, *largs):
        if not self.source:
            self.texture = None
        else:
            filename = resource_find(self.source)
            self._loops = 0
            if filename is None:
                return Logger.error('Image: Error reading file {filename}'.
                                    format(filename=self.source))
            mipmap = self.mipmap
            if self._coreimage is not None:
                self._coreimage.unbind(on_texture=self._on_tex_change)
            try:
                if PY2 and isinstance(filename, str):
                    filename = filename.decode('utf-8')
                self._coreimage = ci = CoreImage(filename, mipmap=mipmap,
                                                 anim_delay=self.anim_delay,
                                                 keep_data=self.keep_data,
                                                 nocache=self.nocache)
            except:
                Logger.error('Image: Error loading texture {filename}'.
                                    format(filename=self.source))
                self._coreimage = ci = None

            if ci:
                ci.bind(on_texture=self._on_tex_change)
                self.texture = ci.texture
예제 #26
0
파일: yuvvideo.py 프로젝트: dev-life/yuvist
 def _do_video_load(self, *largs):
     if self._video:
         self._video.stop()
     if not self.source:
         self._video   = None
         self.textures = [None, None, None]
         self.texture  = None
     else:
         filename = self.source
         if filename.split(':')[0] not in (
                 'http', 'https', 'file', 'udp', 'rtp', 'rtsp'):
             filename = resource_find(filename)
         self._video = VideoYuv(filename=filename,
                                format=self.format,
                                colorfmt=self.colorfmt,
                                size=self.yuv_size,
                                fps=self.yuv_fps)
         self._video.volume = self.volume
         self._video.bind(on_load=self._on_video_load,
                          on_frame=self._on_video_frame,
                          on_eos=self._on_eos)
         if self.state == 'play' or self.play:
             self._video.play()
         self.duration = 1.
         self.position = 0.
예제 #27
0
파일: __init__.py 프로젝트: pylover/kivy
    def register(name, fn_regular, fn_italic=None, fn_bold=None,
                 fn_bolditalic=None):
        '''Register an alias for a Font.

        .. versionadded:: 1.1.0

        If you're using a ttf directly, you might not be able to use the
        bold/italic properties of
        the ttf version. If the font is delivered in multiple files
        (one regular, one italic and one bold), then you need to register these
        files and use the alias instead.

        All the fn_regular/fn_italic/fn_bold parameters are resolved with
        :func:`kivy.resources.resource_find`. If fn_italic/fn_bold are None,
        fn_regular will be used instead.
        '''

        fonts = []

        for font_type in fn_regular, fn_italic, fn_bold, fn_bolditalic:
            if font_type is not None:
                font = resource_find(font_type)

                if font is None:
                    raise IOError('File {0}s not found'.format(font_type))
                else:
                    fonts.append(font)
            else:
                fonts.append(fonts[-1])  # add regular font to list again

        LabelBase._fonts[name] = tuple(fonts)
예제 #28
0
파일: image.py 프로젝트: arasbm/kivy
 def on_source(self, instance, value):
     if not value:
         self.texture = None
     else:
         filename = resource_find(value)
         image = CoreImage(filename)
         self.texture = image.texture
예제 #29
0
파일: builder.py 프로젝트: udiboy1209/kivy
    def load_file(self, filename, **kwargs):
        '''Insert a file into the language builder and return the root widget
        (if defined) of the kv file.

        :parameters:
            `rulesonly`: bool, defaults to False
                If True, the Builder will raise an exception if you have a root
                widget inside the definition.
        '''
        filename = resource_find(filename) or filename
        if __debug__:
            trace('Lang: load file %s' % filename)
        with open(filename, 'r') as fd:
            kwargs['filename'] = filename
            data = fd.read()

            # remove bom ?
            if PY2:
                if data.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)):
                    raise ValueError('Unsupported UTF16 for kv files.')
                if data.startswith((codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)):
                    raise ValueError('Unsupported UTF32 for kv files.')
                if data.startswith(codecs.BOM_UTF8):
                    data = data[len(codecs.BOM_UTF8):]

            return self.load_string(data, **kwargs)
예제 #30
0
파일: window_sdl2.py 프로젝트: TangTab/kivy
    def _set_shape(self, shape_image, mode='default',
                   cutoff=False, color_key=None):
        modes = ('default', 'binalpha', 'reversebinalpha', 'colorkey')
        color_key = color_key or (0, 0, 0, 1)
        if mode not in modes:
            Logger.warning(
                'Window: shape mode can be only '
                '{}'.format(', '.join(modes))
            )
            return
        if not isinstance(color_key, (tuple, list)):
            return
        if len(color_key) not in (3, 4):
            return
        if len(color_key) == 3:
            color_key = (color_key[0], color_key[1], color_key[2], 1)
            Logger.warning(
                'Window: Shape color_key must be only tuple or list'
            )
            return
        color_key = (
            color_key[0] * 255,
            color_key[1] * 255,
            color_key[2] * 255,
            color_key[3] * 255
        )

        assert cutoff in (1, 0)
        shape_image = shape_image or Config.get('kivy', 'window_shape')
        shape_image = resource_find(shape_image) or shape_image
        self._win.set_shape(shape_image, mode, cutoff, color_key)
예제 #31
0
    def __init__(self, *args, **kwargs):
        super(LineRenderer, self).__init__(**kwargs)

        self.render_context.shader.source = resource_find('line_renderer.glsl')
        self.mesh = Mesh(fmt=[(b'v_pos', 2, 'float'), (b'v_parm', 1, 'float')])
        self.mesh.mode = 'lines'

        self.render_context.add(self.mesh)

        self.updateModelViewMatrix()
예제 #32
0
파일: app.py 프로젝트: ire-and-curses/kivy
    def load_kv(self, filename=None):
        '''This method is invoked the first time the app is being run if no
        widget tree has been constructed before for this app.
        This method then looks for a matching kv file in the same directory as
        the file that contains the application class.

        For example, if you have a file named main.py that contains::

            class ShowcaseApp(App):
                pass

        This method will search for a file named `showcase.kv` in
        the directory that contains main.py. The name of the kv file has to be
        the lowercase name of the class, without the 'App' postfix at the end
        if it exists.

        You can define rules and a root widget in your kv file::

            <ClassName>: # this is a rule
                ...

            ClassName: # this is a root widget
                ...

        There must be only one root widget. See the :doc:`api-kivy.lang`
        documentation for more information on how to create kv files. If your
        kv file contains a root widget, it will be used as self.root, the root
        widget for the application.
        '''
        # Detect filename automatically if it was not specified.
        if filename:
            filename = resource_find(filename)
        else:
            try:
                default_kv_directory = dirname(getfile(self.__class__))
                if default_kv_directory == '':
                    default_kv_directory = '.'
            except TypeError:
                # if it's a builtin module.. use the current dir.
                default_kv_directory = '.'
            kv_directory = self.options.get('kv_directory', default_kv_directory)
            clsname = self.__class__.__name__
            if clsname.endswith('App'):
                clsname = clsname[:-3]
            filename = join(kv_directory, '%s.kv' % clsname.lower())

        # Load KV file
        Logger.debug('App: Loading kv <{0}>'.format(filename))
        if not exists(filename):
            Logger.debug('App: kv <%s> not found' % filename)
            return False
        root = Builder.load_file(filename)
        if root:
            self.root = root
        return True
예제 #33
0
    def __init__(self, **kwargs):
        self.shadow = kwargs.get("shadow", False)
        global PICKING_BUFFER_SIZE
        PICKING_BUFFER_SIZE = kwargs.get("canvas_size", Window.size)
        self.shadow = True
        self.picking = True
        self.co = self.canvas
        self.canvas = RenderContext(compute_normal_mat=False)

        #self.canvas.shader.source = resource_find('./kivy3dgui/gles2.0/shaders/simple_no_light.glsl')
        self.canvas.shader.source = resource_find(
            './kivy3dgui/gles2.0/toonshader/toon.glsl')
        self.alpha = 0.0
        self._touches = []
        with self.canvas:
            self._translate = Translate(0, 0, 0)
            self._rotate = Rotate(0.0, 1.0, 0.0, 0.0)
            PushMatrix()
            self.cbs = Callback(self.setup_gl_context)

            if self.shadow:
                self.create_fbo()
            if self.picking:
                self.create_picking_fbo()
            self.create_motion_blur()

        with self.canvas.before:
            self.cbs = Callback(self.setup_gl_context)
            if self.shadow:
                BindTexture(texture=self.fbo.texture, index=1)
                BindTexture(texture=self.motion_blur_fbo.texture, index=5)

            PushMatrix()

            self.setup_scene()
            PopMatrix()
            PushMatrix()
            self.cc = Callback(self.check_context)
            PopMatrix()
            UpdateNormalMatrix()

        with self.canvas.after:
            self.cbr = Callback(self.reset_gl_context)
            PopMatrix()
            #Fixing Shadow and Picking
        self.shadow = True
        self.picking = True
        if self.shadow:
            self.init_fbo()
        if self.picking:
            self.init_picking()
        self.init_motion_blur()
        super(Canvas3D, self).__init__(**kwargs)
        Clock.schedule_interval(self.update_glsl, 1 / 60.)
        self._touches = {}
예제 #34
0
    def draw_keys(self):
        layout = self.available_layouts[self.layout]
        layout_rows = layout['rows']
        layout_geometry = self.layout_geometry
        layout_mode = self.layout_mode

        # draw background
        background = resource_find(self.background_disabled
                                   if self.disabled else
                                   self.background)
        texture = Image(background, mipmap=True).texture
        self.background_key_layer.clear()
        with self.background_key_layer:
            Color(*self.background_color)
            BorderImage(texture=texture, size=self.size,
                        border=self.background_border)

        # XXX separate drawing the keys and the fonts to avoid
        # XXX reloading the texture each time

        # first draw keys without the font
        key_normal = resource_find(self.key_background_disabled_normal
                                   if self.disabled else
                                   self.key_background_normal)
        texture = Image(key_normal, mipmap=True).texture
        with self.background_key_layer:
            Color(*self.key_background_color)
            for line_nb in range(1, layout_rows + 1):
                for pos, size in layout_geometry['LINE_%d' % line_nb]:
                    BorderImage(texture=texture, pos=pos, size=size,
                                border=self.key_border)

        # then draw the text
        for line_nb in range(1, layout_rows + 1):
            key_nb = 0
            for pos, size in layout_geometry['LINE_%d' % line_nb]:
                # retrieve the relative text
                text = layout[layout_mode + '_' + str(line_nb)][key_nb][0]
                z = Label(text=text, font_size=self.font_size, pos=pos,
                           size=size, font_name=self.font_name)
                self.add_widget(z)
                key_nb += 1
 def redraw_board(self):
     self.update_board()
     # clearing out widgets that made up the previous board display
     self.board_grid.clear_widgets()
     for j in range(5):
         for i in range(5):
             # adding yellow piece if current space belongs to user
             if self.board[4 - j][i] == self.piece:
                 self.board_grid.add_widget(
                     Image(source=resource_find(
                         "images/connect4/bestchipyellow.png")))
             # adding red piece if current space belongs to AI
             elif self.board[4 - j][i] == self.opponent:
                 self.board_grid.add_widget(
                     Image(source=resource_find(
                         "images/connect4/bestchipred.png")))
             # adding blank image for empty space
             else:
                 self.board_grid.add_widget(
                     Image(source="", color=(0, 0, 0)))
예제 #36
0
def atlas_texture_exists(uri):
    try:
        textures = get_atlas_textures(
            resource_find(dirname(uri).replace("atlas://", "") + ".atlas"))
        return basename(uri) in textures
    except OSError:
        return False
    except:
        print "EXCEPTION IN atlas_texture_exists"

        traceback.print_exc()
예제 #37
0
 def load(filename):
     '''Load a sound, and return a Sound() instance'''
     rfn = resource_find(filename)
     if rfn is not None:
         filename = rfn
     ext = filename.split('.')[-1].lower()
     for classobj in SoundLoader._classes:
         if ext in classobj.extensions():
             return classobj(source=filename)
     Logger.warning('Audio: Unable to find a loader for <%s>' % filename)
     return None
예제 #38
0
class Example(MDApp):
    path_to_kv_file = resource_find("my.kv")
    print(path_to_kv_file)

    def build(self):
        self.theme_cls.theme_style = "Dark"
        return Builder.load_string(KV)

    def update_kv_file(self, text):
        with open(self.path_to_kv_file, "w") as kv_file:
            kv_file.write(text)
예제 #39
0
def load_domains(program_type):
    file_string = ""
    with open(resource_find(f'data/{program_type}/Domains.txt'), 'r') as file:
        for line in file:
            file_string += line
    domains = []
    domain_data = file_string.split('-\n')
    for domain in domain_data:
        name, description, small_description = domain.split('~\n')
        domains.append(Domain(name.strip(), description.strip(), small_description.strip()))
    return domains
예제 #40
0
    def add(self, res_name: str):
        res = resource_find(res_name)
        if res is None:
            raise RuntimeError(f"Couldn't find resource {res_name}")
        sound = SoundLoader.load(res)
        if sound is None:
            raise RuntimeError(f"Failed at loading sound '{res_name}'!")

        print(
            f"Added '{res_name}' ({sound.length} seconds) to bucket-o-sounds")
        self._sounds.append(sound)
예제 #41
0
파일: image.py 프로젝트: SparrowG/kivy
 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
예제 #42
0
 def _load_from_source(self, *args):
     '''(internal) Loads the glsl string from a source file.'''
     source = self.source
     if not source:
         return
     filename = resource_find(source)
     if filename is None:
         return Logger.error(
             'Error reading file {filename}'.format(filename=source))
     with open(filename) as fileh:
         self.glsl = fileh.read()
예제 #43
0
파일: __init__.py 프로젝트: lcm337/kivy
    def register(name,
                 fn_regular,
                 fn_italic=None,
                 fn_bold=None,
                 fn_bolditalic=None):
        '''Register an alias for a Font.

        .. versionadded:: 1.1.0

        If you're using directly a ttf, you might not be able to use bold/italic
        of the ttf version. If the font is delivered with different version of
        it (one regular, one italic and one bold), then you need to register it
        and use the alias instead.

        All the fn_regular/fn_italic/fn_bold parameters are resolved with
        :func:`kivy.resources.resource_find`. If fn_italic/fn_bold are None,
        fn_regular will be used instead.
        '''
        _fn_regular = resource_find(fn_regular)
        if _fn_regular is None:
            raise IOError('File %r not found' % fn_regular)
        if fn_italic is None:
            _fn_italic = _fn_regular
        else:
            _fn_italic = resource_find(fn_italic)
            if _fn_italic is None:
                raise IOError('File %r not found' % fn_italic)
        if fn_bold is None:
            _fn_bold = _fn_regular
        else:
            _fn_bold = resource_find(fn_bold)
            if _fn_bold is None:
                raise IOError('File %r not found' % fn_bold)
        if fn_bolditalic is None:
            _fn_bolditalic = _fn_regular
        else:
            _fn_bolditalic = resource_find(fn_bolditalic)
            if _fn_bolditalic is None:
                raise IOError('Label: File %r not found' % fn_bolditalic)
        LabelBase._fonts[name] = (_fn_regular, _fn_italic, _fn_bold,
                                  _fn_bolditalic)
예제 #44
0
def get_mod(modname,moddir):
    mod_str = ''
    resource_add_path(moddir)
    modpath = resource_find(modname + '.module')
    print 'Manjeet: modpath ',modpath
    if modpath == None:
        print 'Module not found' , modpath
        return mod_str
    with open(modpath,'r') as mf:
        mod_str += mf.read()
    print 'Manjeet: module str:\n', mod_str
    return mod_str
예제 #45
0
 def update_glsl(self, *largs):
     asp = self.size[0] / float(self.size[1])
     proj = Matrix().view_clip(-asp, asp, -1, 1, 1, 100, 1)
     model = Matrix().look_at(0.0, 0.0, 0.25, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)
     with self.canvas:
         self.fbo.shader.source = resource_find('simple.glsl')
         self.fbo['projection_mat'] = proj
         self.fbo['modelview_mat'] = model
         self.rot.angle += -1
         self.texture = self.fbo.texture
     with self.fbo:
         BindTexture(source='testure.jpg', index=1)
예제 #46
0
파일: label.py 프로젝트: wilsaj/kivy
 def _trigger_texture_update(self, name=None, source=None, value=None):
     if source:
         if name == 'text':
             self._label.text = value
         elif name == 'text_size':
             self._label.usersize = value
         elif name == 'font_name':
             rvalue = resource_find(value)
             self._label.options['font_name'] = rvalue if rvalue else value
         else:
             self._label.options[name] = value
     self._trigger_texture()
 def __init__(self, environment, difficulty, policy = 'max'):
     self.environment = environment
     self.policy = policy
     self.Q = ''
     self.first = None
     if policy == 'max':
         with open(resource_find(f"game_logic\\tictactoeAI\\qtables\\{difficulty}.txt"), 'r') as f:
             for i in f.readlines():
                 self.Q = i
         self.Q = eval(self.Q)
     self.Q = defaultdict(lambda: 0.0, self.Q)
     self.reset_past()
예제 #48
0
    def __init__(self, **kwargs):
        self.canvas = Canvas()
        with self.canvas:
            self.fbo = Fbo(size=self.size,
                           with_depthbuffer=True,
                           compute_normal_mat=True,
                           clear_color=(0., 0., 0., 0.))

            self.viewport = Rectangle(size=self.size, pos=self.pos)

        self.fbo.shader.source = resource_find(
            join(dirname(__file__), 'simple.glsl'))
        super(ObjectRenderer, self).__init__(**kwargs)
예제 #49
0
    def __init__(self, **kwargs):
        self.canvas = RenderContext(compute_normal_mat=True)
        #self.scene = ObjFileLoader(resource_find("resource/models/car-kart-white.obj"))
        self.scene = ObjFileLoader(resource_find("resource/models/car-formula-white.obj"))
        #self.scene = ObjFileLoader(resource_find("resource/models/car-parsche-sport-white.obj"))
#TODO: the following needs work
        #self.scene = ObjFileLoader(resource_find("resource/models/car-groupc-2-white.obj"))
        #self.scene = ObjFileLoader(resource_find("resource/models/car-groupc-1-white.obj"))

        self.canvas.shader.source = resource_find('resource/models/shaders.glsl')
        super(ImuView, self).__init__(**kwargs)
        with self.canvas:
            self.cb = Callback(self.setup_gl_context)
            PushMatrix()
            self.setup_scene()
            PopMatrix()
            self.cb = Callback(self.reset_gl_context)
        self.camera_translate = [0, 0, -2.5]
        self.camera_ax = 0
        self.camera_ay = 0
        Clock.schedule_once(self.update_glsl, .5 )    
        self._touches = []
예제 #50
0
    def __init__(self, **kwargs):
        self.canvas = Canvas()
        self.scene = ObjFileLoader(resource_find("brain.obj"))

        self.meshes = []

        with self.canvas:
            self.fbo = Fbo(size=self.size,
                           with_depthbuffer=True,
                           compute_normal_mat=True,
                           clear_color=(0., 0., 0., 0.))
            self.viewport = Rectangle(size=self.size, pos=(0, -150))
        self.fbo.shader.source = resource_find('simple.glsl')

        super(Renderer, self).__init__(**kwargs)

        with self.fbo:
            self.cb = Callback(self.setup_gl_context)
            PushMatrix()
            self.setup_scene()
            PopMatrix()
            self.cb = Callback(self.reset_gl_context)
예제 #51
0
 def __init__(self, **kwargs):
     super(ServerSettings, self).__init__(**kwargs)
     config = ConfigParser()
     config.read('serverconfig.ini')
     config.setdefaults('main', {
         'root': '/sdcard',
         'allow_uploads': False,
         'port': 11451
     })
     s = SettingsWithNoMenu()
     s.add_json_panel('Server', config, resource_find('settings.json'))
     s.on_config_change = restart_server
     self.add_widget(s)
예제 #52
0
 def load_wav(self, filename):
     """Use SDL2 to load wav files cuz it's better, but only on windows"""
     rfn = resource_find(filename)
     sound = None
     if rfn is not None:
         filename = rfn
     if platform == 'win':
         sound = SoundSDL2(source=filename)
     else:
         sound = SoundLoader.load(filename)
         sound.unload(
         )  # We don't need to keep these loaded all the time... On linux.
     return sound
def load_fontawesome_unichr():
    """
    Load FontAwesome icon names and their associated unicode
    """

    fa = FontAwesomeIconDict()

    with open(resource_find('FontAwesomeUnichr.txt'), 'Ur') as f:
        for line in f:
            k, _, v = line.partition(" ")
            fa[k] = unichr(int(v, 16))

    return fa
예제 #54
0
    def test_reload_asyncimage(self):
        from kivy.resources import resource_find
        from tempfile import mkdtemp
        from os import remove
        from shutil import copyfile, rmtree

        fn = resource_find('data/logo/kivy-icon-16.png')
        t = mkdtemp()
        source = join(t, 'source.png')
        copyfile(fn, source)
        image = AsyncImage(source=source)
        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)
        image.reload()
        self.render(image, framecount=2)
        self.assertEqual(image.texture_size, [32, 32])
        remove(source)
        rmtree(t)
예제 #55
0
파일: image.py 프로젝트: kod3r/kivy
 def on_source(self, instance, value):
     if not value:
         if self._coreimage is not None:
             self._coreimage.unbind(on_texture=self._on_tex_change)
         self.texture = None
         self._coreimage = None
     else:
         if not self.is_uri(value):
             value = resource_find(value)
         self._coreimage = image = Loader.image(value)
         image.bind(on_load=self.on_source_load)
         image.bind(on_texture=self._on_tex_change)
         self.texture = image.texture
예제 #56
0
파일: d3tex2.py 프로젝트: jacky4566/ykpilot
    def __init__(self, **kwargs):
        self.gui = None

        self.canvas = RenderContext(compute_normal_mat=True)
        self.canvas.shader.source = resource_find('simple.glsl')

        self.d3h = D3Helper()
        self.d3h.loadObj([
            [
                'boat', "./3dModels/boat2_3dex_boat.obj",
                "./3dModels/oiysh_profile2.jpeg"
            ],
            ['roseta', './3dModels/3d_roseta.obj', ''],
            [
                'genoa', "./3dModels/boat2_3dex_sailGenoa_onPower.obj",
                "./3dModels/3d_texture_genoa.jpg"
            ],
            [
                'main', "./3dModels/boat2_3dex_sailMain_sailup_onPower.obj",
                "./3dModels/IMG_5410.jpg"
            ],
            ['boom', "./3dModels/boat2_3dex_boom.obj", ""],
            ['ruder', "./3dModels/boat2_3dex_ruder.obj", ""],
            ['tiler', "./3dModels/boat2_3dex_tiler.obj", ""],
            #['hdr1','./3dModels/hdr1.obj','./3dModels/hdr1.png'],
            ['xAxis', './3dModels/x-axis.obj', './3dModels/red.png'],
            ['yAxis', './3dModels/y-axis.obj', './3dModels/green.png'],
            ['zAxis', './3dModels/z-axis.obj', './3dModels/blue.png'],
            ['box', './3dModels/3d_box.obj', ''],
            [
                'waterTile', './3dModels/waterTile.obj',
                "./3dModels/IMG_5410.jpg"
            ],
            [
                'hdr2', './3dModels/hdr2.obj',
                "./3dModels/PANO_20160311_160253.jpg"
            ],
            ['kap2', './3dModels/tile.obj', "./3dModels/kap2.png"]
        ])

        super(d3tex2, self).__init__(**kwargs)

        with self.canvas:
            self.cb = Callback(self.setup_gl_context)
            PushMatrix()
            self.setup_scene()
            PopMatrix()
            self.cb = Callback(self.reset_gl_context)

        if d3tex2RunAlone:
            self.on_displayNow()
예제 #57
0
    def __init__(self, *args, **kwargs):
        super(GraphRenderer, self).__init__(**kwargs)
        self.render_context.shader.source = resource_find(
            'graph_renderer.glsl')

        self.mesh = Mesh(fmt=[('v_pos', 2, 'float')])
        self.mesh.mode = 'lines'
        # glLineWidth(5.0);
        self.N = 0
        self.render_context.add(self.mesh)

        self.xmin = 0.0
        self.xmax = 1.0
        self.updateModelViewMatrix()
예제 #58
0
    def refresh_active_keys_layer(self):
        self.active_keys_layer.clear()

        active_keys = self.active_keys
        layout_geometry = self.layout_geometry
        background = resource_find(self.key_background_down)
        texture = Image(background, mipmap=True).texture

        with self.active_keys_layer:
            Color(*self.key_background_color)
            for line_nb, index in active_keys.values():
                pos, size = layout_geometry['LINE_%d' % line_nb][index]
                BorderImage(texture=texture, pos=pos, size=size,
                            border=self.key_border)
예제 #59
0
파일: image.py 프로젝트: kod3r/kivy
 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
         if self._coreimage is not None:
             self._coreimage.unbind(on_texture=self._on_tex_change)
         self._coreimage = ci = CoreImage(filename, mipmap=mipmap,
                 anim_delay=self.anim_delay)
         ci.bind(on_texture=self._on_tex_change)
         self.texture = ci.texture
예제 #60
0
파일: __main__.py 프로젝트: xashes/katrain
    def build(self):
        self.icon = ICON  # how you're supposed to set an icon

        self.title = f"KaTrain v{VERSION}"
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Gray"
        self.theme_cls.primary_hue = "200"

        kv_file = find_package_resource("katrain/gui.kv")
        popup_kv_file = find_package_resource("katrain/popups.kv")
        resource_add_path(PATHS["PACKAGE"] + "/fonts")
        resource_add_path(PATHS["PACKAGE"] + "/sounds")
        resource_add_path(PATHS["PACKAGE"] + "/img")
        resource_add_path(os.path.abspath(
            os.path.expanduser(DATA_FOLDER)))  # prefer resources in .katrain

        theme_file = resource_find("theme.json")
        if theme_file:
            try:
                with open(theme_file) as f:
                    theme_overrides = json.load(f)
                for k, v in theme_overrides.items():
                    setattr(Theme, k, v)
                    print(f"[{theme_file}] Found theme override {k} = {v}")
            except Exception as e:  # noqa E722
                print(f"Failed to load theme file {theme_file}: {e}")

        Theme.DEFAULT_FONT = resource_find(Theme.DEFAULT_FONT)
        Builder.load_file(kv_file)

        Window.bind(on_request_close=self.on_request_close)
        Window.bind(on_dropfile=lambda win, file: self.gui.load_sgf_file(
            file.decode("utf8")))

        self.gui = KaTrainGui()
        Builder.load_file(popup_kv_file)
        return self.gui