cachewebview.cpp 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include "cachewebview.h"
  2. #include <QtGui>
  3. CacheWebView::CacheWebView(QWidget *parent) :
  4. QWebView(parent)
  5. {
  6. cache = 0;
  7. isCacheFile = false;
  8. m_isloading = false;
  9. setAcceptDrops(false);
  10. QObject::connect(this,SIGNAL(linkClicked(QUrl)),this,SLOT(onLinkClicked(QUrl)));
  11. }
  12. void CacheWebView::setPageUrl(QString pageUrl, QString cachePath)
  13. {
  14. if(pageUrl.isEmpty())
  15. return;
  16. this->pageUrl = pageUrl;
  17. this->cachePath = cachePath;
  18. QUrl url(pageUrl);
  19. connect(this,SIGNAL(loadFinished(bool)),this,SLOT(onWebViewFinished(bool)));
  20. this->page()->setLinkDelegationPolicy(QWebPage::DelegateExternalLinks);
  21. this->load(url);
  22. }
  23. CacheWebView::~CacheWebView()
  24. {
  25. if(cache)
  26. {
  27. cache->abort();
  28. cache->wait();
  29. delete cache;
  30. cache = 0;
  31. }
  32. qDebug()<<QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")\
  33. <<"CacheWebView Destroyed.";
  34. }
  35. void CacheWebView::onLinkClicked(QUrl url)
  36. {
  37. QDesktopServices::openUrl(url);
  38. }
  39. void CacheWebView::onWebViewFinished(bool ok)
  40. {
  41. m_isloading = false;
  42. disconnect(this,SIGNAL(loadFinished(bool)),this,SLOT(onWebViewFinished(bool)));
  43. if(!isCacheFile)
  44. {
  45. if(ok)
  46. {
  47. if(!cache)
  48. {
  49. cache = new CacheWebPage(this->pageUrl,QCoreApplication::applicationDirPath()+"/../cache/");
  50. }
  51. cache->start();
  52. }
  53. else
  54. {
  55. isCacheFile = true;
  56. displayCacheFile();
  57. }
  58. }
  59. }
  60. void CacheWebView::displayCacheFile()
  61. {
  62. QUrl url(this->pageUrl);
  63. QString md5;
  64. QByteArray ba;
  65. ba = QCryptographicHash::hash ( this->pageUrl.toAscii(), QCryptographicHash::Md5 );
  66. md5.append(ba.toHex());
  67. QString cacheFile = QCoreApplication::applicationDirPath()+"/../cache/" + md5 + url.path();
  68. if(QFile::exists(cacheFile))
  69. {
  70. this->load(QUrl::fromUserInput(cacheFile));
  71. }
  72. }