]> git.tdb.fi Git - libs/gui.git/blob - source/graphics/imageloader.cpp
Call setActivationPolicy to make non-bundled programs work
[libs/gui.git] / source / graphics / imageloader.cpp
1 #include <msp/core/refptr.h>
2 #include <msp/io/file.h>
3 #include <msp/strings/format.h>
4 #include "imageloader.h"
5
6 using namespace std;
7
8 namespace Msp {
9 namespace Graphics {
10
11 bool ImageLoader::registered_loaders_changed = false;
12
13 ImageLoader::ImageLoader():
14         source(0)
15 { }
16
17 ImageLoader::~ImageLoader()
18 {
19         delete source;
20 }
21
22 ImageLoader *ImageLoader::open_file(const string &fn)
23 {
24         try
25         {
26                 RefPtr<IO::BufferedFile> file = new IO::BufferedFile(fn);
27                 ImageLoader *loader = open_io(*file);
28                 loader->source = file.release();
29                 return loader;
30         }
31         catch(const unsupported_image_format &e)
32         {
33                 throw unsupported_image_format(format("%s: %s", fn, e.what()));
34         }
35 }
36
37 ImageLoader *ImageLoader::open_io(IO::Seekable &io)
38 {
39         list<RegisterBase *> &loaders = get_registered_loaders();
40         if(registered_loaders_changed)
41         {
42                 registered_loaders_changed = false;
43                 loaders.sort(signature_size_compare);
44         }
45
46         vector<char> sig_buf(loaders.back()->get_signature_size());
47         unsigned sig_len = io.read(&sig_buf[0], sig_buf.size());
48         string signature(sig_buf.begin(), sig_buf.end());
49
50         ImageLoader *loader = 0;
51         for(list<RegisterBase *>::const_iterator i=loaders.begin(); (!loader && i!=loaders.end()); ++i)
52                 if((*i)->detect(signature))
53                         loader = (*i)->create(io);
54
55         io.seek(0, IO::S_BEG);
56
57         if(!loader)
58         {
59                 string sig_hex;
60                 for(unsigned i=0; i<sig_len; ++i)
61                 {
62                         if(i)
63                                 sig_hex += ' ';
64                         sig_hex += format("%02X", static_cast<unsigned char>(sig_buf[i]));
65                 }
66                 throw unsupported_image_format(sig_hex);
67         }
68
69         return loader;
70 }
71
72
73 ImageLoader::RegisterBase::RegisterBase()
74 {
75         get_registered_loaders().push_back(this);
76         registered_loaders_changed = true;
77 }
78
79
80 list<ImageLoader::RegisterBase *> &ImageLoader::get_registered_loaders()
81 {
82         static list<RegisterBase *> regs;
83         return regs;
84 }
85
86 bool ImageLoader::signature_size_compare(RegisterBase *r1, RegisterBase *r2)
87 {
88         return r1->get_signature_size()<r2->get_signature_size();
89 }
90
91 } // namespace Graphics
92 } // namespace Msp