ResourceLoader.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <AK/SharedBuffer.h>
  2. #include <LibCore/CFile.h>
  3. #include <LibHTML/ResourceLoader.h>
  4. #include <LibProtocol/Client.h>
  5. #include <LibProtocol/Download.h>
  6. ResourceLoader& ResourceLoader::the()
  7. {
  8. static ResourceLoader* s_the;
  9. if (!s_the)
  10. s_the = &ResourceLoader::construct().leak_ref();
  11. return *s_the;
  12. }
  13. ResourceLoader::ResourceLoader()
  14. : m_protocol_client(LibProtocol::Client::construct())
  15. {
  16. }
  17. void ResourceLoader::load(const URL& url, Function<void(const ByteBuffer&)> callback)
  18. {
  19. if (url.protocol() == "file") {
  20. auto f = CFile::construct();
  21. f->set_filename(url.path());
  22. if (!f->open(CIODevice::OpenMode::ReadOnly)) {
  23. dbg() << "ResourceLoader::load: Error: " << f->error_string();
  24. callback({});
  25. return;
  26. }
  27. auto data = f->read_all();
  28. deferred_invoke([data = move(data), callback = move(callback)](auto&) {
  29. callback(data);
  30. });
  31. return;
  32. }
  33. if (url.protocol() == "http") {
  34. auto download = protocol_client().start_download(url.to_string());
  35. download->on_finish = [this, callback = move(callback)](bool success, const ByteBuffer& payload, auto) {
  36. --m_pending_loads;
  37. if (on_load_counter_change)
  38. on_load_counter_change();
  39. if (!success) {
  40. dbg() << "HTTP load failed!";
  41. callback({});
  42. return;
  43. }
  44. callback(ByteBuffer::copy(payload.data(), payload.size()));
  45. };
  46. ++m_pending_loads;
  47. if (on_load_counter_change)
  48. on_load_counter_change();
  49. return;
  50. }
  51. dbg() << "Unimplemented protocol: " << url.protocol();
  52. ASSERT_NOT_REACHED();
  53. }