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);
47 throw unsupported_image_format("no loaders");
49 vector<char> sig_buf(loaders.back()->get_signature_size());
50 unsigned sig_len = io.read(&sig_buf[0], sig_buf.size());
51 string signature(sig_buf.begin(), sig_buf.end());
53 ImageLoader *loader = 0;
54 for(list<RegisterBase *>::const_iterator i=loaders.begin(); (!loader && i!=loaders.end()); ++i)
55 if((*i)->detect(signature))
56 loader = (*i)->create(io);
58 io.seek(0, IO::S_BEG);
63 for(unsigned i=0; i<sig_len; ++i)
67 sig_hex += format("%02X", static_cast<unsigned char>(sig_buf[i]));
69 throw unsupported_image_format(sig_hex);
76 ImageLoader::RegisterBase::RegisterBase()
78 get_registered_loaders().push_back(this);
79 registered_loaders_changed = true;
83 list<ImageLoader::RegisterBase *> &ImageLoader::get_registered_loaders()
85 static list<RegisterBase *> regs;
89 bool ImageLoader::signature_size_compare(RegisterBase *r1, RegisterBase *r2)
91 return r1->get_signature_size()<r2->get_signature_size();
94 } // namespace Graphics