1 /**************************************************************************
2 * Otter Browser: Web browser controlled by the user, not vice-versa.
3 * Copyright (C) 2018 - 2019 Michal Dutkiewicz aka Emdek <michal@emdek.pl>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 **************************************************************************/
19 
20 #include "TextBrowserWidget.h"
21 #include "../core/Job.h"
22 #include "../core/NetworkCache.h"
23 #include "../core/NetworkManagerFactory.h"
24 
25 namespace Otter
26 {
27 
TextBrowserWidget(QWidget * parent)28 TextBrowserWidget::TextBrowserWidget(QWidget *parent) : QTextBrowser(parent),
29 	m_imagesPolicy(AllImages)
30 {
31 }
32 
setImagesPolicy(TextBrowserWidget::ImagesPolicy policy)33 void TextBrowserWidget::setImagesPolicy(TextBrowserWidget::ImagesPolicy policy)
34 {
35 	m_imagesPolicy = policy;
36 
37 	if (document())
38 	{
39 		document()->adjustSize();
40 	}
41 }
42 
loadResource(int type,const QUrl & url)43 QVariant TextBrowserWidget::loadResource(int type, const QUrl &url)
44 {
45 	if ((type == QTextDocument::ImageResource && m_imagesPolicy == NoImages) || (type != QTextDocument::ImageResource && type != QTextDocument::StyleSheetResource))
46 	{
47 		return {};
48 	}
49 
50 	const QVariant result(QTextBrowser::loadResource(type, url));
51 
52 	if (!result.isNull() || m_resources.contains(url))
53 	{
54 		return result;
55 	}
56 
57 	if (type == QTextDocument::ImageResource && m_imagesPolicy == OnlyCachedImages)
58 	{
59 		NetworkCache *cache(NetworkManagerFactory::getCache());
60 
61 		if (cache)
62 		{
63 			QIODevice *device(cache->data(url));
64 
65 			if (device)
66 			{
67 				const QByteArray resourceData(device->readAll());
68 
69 				device->deleteLater();
70 
71 				return resourceData;
72 			}
73 		}
74 
75 		return {};
76 	}
77 
78 	m_resources.insert(url);
79 
80 	DataFetchJob *job(new DataFetchJob(url, this));
81 
82 	connect(job, &DataFetchJob::jobFinished, [=](bool isSuccess)
83 	{
84 		if (isSuccess)
85 		{
86 			document()->addResource(type, url, job->getData()->readAll());
87 			document()->adjustSize();
88 		}
89 	});
90 
91 	job->start();
92 
93 	return {};
94 }
95 
96 }
97