1 #include <msp/core/refptr.h>
2 #include <msp/io/file.h>
3 #include <msp/strings/format.h>
4 #include "imageloader.h"
11 bool ImageLoader::registered_loaders_changed = false;
13 ImageLoader::ImageLoader():
17 ImageLoader::~ImageLoader()
22 ImageLoader *ImageLoader::open_file(const string &fn)
26 RefPtr<IO::BufferedFile> file = new IO::BufferedFile(fn);
27 ImageLoader *loader = open_io(*file);
28 loader->source = file.release();
31 catch(const unsupported_image_format &e)
33 throw unsupported_image_format(format("%s: %s", fn, e.what()));
37 ImageLoader *ImageLoader::open_io(IO::Seekable &io)
39 list<RegisterBase *> &loaders = get_registered_loaders();
40 if(registered_loaders_changed)
42 registered_loaders_changed = false;
43 loaders.sort(signature_size_compare);
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());
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);
55 io.seek(0, IO::S_BEG);
60 for(unsigned i=0; i<sig_len; ++i)
64 sig_hex += format("%02X", static_cast<unsigned char>(sig_buf[i]));
66 throw unsupported_image_format(sig_hex);
73 ImageLoader::RegisterBase::RegisterBase()
75 get_registered_loaders().push_back(this);
76 registered_loaders_changed = true;
80 list<ImageLoader::RegisterBase *> &ImageLoader::get_registered_loaders()
82 static list<RegisterBase *> regs;
86 bool ImageLoader::signature_size_compare(RegisterBase *r1, RegisterBase *r2)
88 return r1->get_signature_size()<r2->get_signature_size();
91 } // namespace Graphics