]> git.tdb.fi Git - libs/gltk.git/blob - source/resources.cpp
Rework how widget ownership works in Container
[libs/gltk.git] / source / resources.cpp
1 #include <msp/fs/utils.h>
2 #include "resources.h"
3
4 using namespace std;
5
6 namespace Msp {
7 namespace GLtk {
8
9 Resources::Resources()
10 {
11         init();
12 }
13
14 Resources::Resources(const FS::Path &fn)
15 {
16         init();
17
18         dir_src = new DataFile::DirectorySource;
19         dir_src->add_directory(FS::dirname(fn));
20         add_source(*dir_src);
21
22         DataFile::load(*this, fn.str());
23 }
24
25 void Resources::init()
26 {
27         default_font = 0;
28         dir_src = 0;
29         add_type<Graphic>().keyword("graphic");
30         add_type<GL::Texture2D>().keyword("texture").creator(&Resources::create_texture);
31         add_type<GL::Font>().keyword("font");
32         add_type<Style>().keyword("style");
33 }
34
35 Resources::~Resources()
36 {
37         delete dir_src;
38 }
39
40 const GL::Font &Resources::get_default_font() const
41 {
42         if(!default_font)
43                 throw logic_error("!default_font");
44
45         return *default_font;
46 }
47
48 GL::Texture2D *Resources::create_texture(const string &name)
49 {
50         string ext = FS::extpart(name);
51         if(ext==".png" || ext==".jpg")
52                 if(IO::Seekable *io = open_from_sources(name))
53                 {
54                         Graphics::Image image;
55                         image.load_io(*io);
56                         delete io;
57
58                         GL::Texture2D *tex = new GL::Texture2D;
59                         tex->set_min_filter(GL::LINEAR);
60                         tex->image(image);
61                         return tex;
62                 }
63
64         return 0;
65 }
66
67
68 Resources::Loader::Loader(Resources &r):
69         Collection::Loader(r),
70         res(r)
71 {
72         add("default_font", &Loader::default_font);
73         add("font", &Loader::font);
74 }
75
76 void Resources::Loader::default_font(const string &name)
77 {
78         res.default_font = &res.get<GL::Font>(name);
79 }
80
81 void Resources::Loader::font(const string &name)
82 {
83         RefPtr<GL::Font> fnt = new GL::Font;
84         load_sub(*fnt, res);
85         res.add(name, fnt.get());
86         if(!res.default_font)
87                 res.default_font = fnt.get();
88         fnt.release();
89 }
90
91 } // namespace GLtk
92 } // namespace Msp