Newer
Older
saori / saoriviewentry.cpp
@TAM (Teppei Tamra) TAM (Teppei Tamra) on 8 Jun 2018 6 KB イメージキャッシュの上限を設定。
/***

The MIT License

Copyright (c) 2018 Teppei Tamra (TAM)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

***/

#include "saoriviewentry.h"
#include "saoriapplication.h"
#include "saoricache.h"
#include "saoridef.h"
#include <QRegExp>
#include <QImage>
#include <QPainter>
#include <QDebug>

QMap<QString,QImage> SaoriViewEntry::m_imagecache_g;

SaoriViewEntry::SaoriViewEntry(QWidget *parent)
{
    SaoriViewEntry(0,parent);
    m_cw = false;
}

SaoriViewEntry::SaoriViewEntry(qlonglong id, QWidget *parent) :
    QTextBrowser(parent)
{
    setReadOnly(true);
    setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
    setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
    setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents);
    setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum);
    setOpenLinks(false);
    setOpenExternalLinks(false);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_id = id;
    connect(SaoriApplication::saori()->cache(),&SaoriCache::downloaded,this,&SaoriViewEntry::downloaded);
    connect(this,&SaoriViewEntry::anchorClicked,this,[&](const QUrl url){
        if (url.toString().left(3) == "cw:") {
            m_cw = m_cw ? false : true;
            setContent(m_original,m_cw);
        }
    });
}

void SaoriViewEntry::setContent(const QString content, bool cw)
{
    m_original = content;
    m_cw = cw;
    document()->clear();
    QStringList imgs;
    for (int i = 0;(i = m_original.indexOf("<img(",i)) != -1;++ i) {
        int p = m_original.indexOf(')',i);
        imgs << m_original.mid(i + 5,p - (i + 5));
    }
    for (auto i:imgs) {
        int p = i.indexOf(':');
        QString imageurl;
        if (i.mid(p + 1,2) != ":/") {
            imageurl = SaoriApplication::saori()->cache()->fileCache(QUrl(i.mid(p + 1)));
        } else {
            imageurl = i.mid(p + 1);
        }
        m_urlmap[i] = imageurl;
        if (m_imagecache_g.contains(i)) {
            document()->addResource(QTextDocument::ImageResource,QUrl("img:" + imageurl),QVariant(m_imagecache_g[i]));
            auto c = m_imagecache_g.take(i);
            m_imagecache_g[i] = c;
        } else if (m_imagecache_l.contains(i)) {
            document()->addResource(QTextDocument::ImageResource,QUrl("img:" + imageurl),QVariant(m_imagecache_l[i]));
        } else {
            QImage img(imageurl);
            imageResizer(i.left(p),img);
            document()->addResource(QTextDocument::ImageResource,QUrl("img:" + imageurl),QVariant(img));
            auto type = i.split(':')[0];
            if (((type == "icon") || (type == "avatar") || (type == "mavatar")) && (imageurl.left(2) != ":/")) {
                if (m_imagecache_g.count() >= 500) m_imagecache_g.take(m_imagecache_g.firstKey());
                m_imagecache_g[i] = img;
            }
            else if (imageurl != SAORI_ICONS_LOADING) m_imagecache_l[i] = img;
        }
    }
    setText(designedText(cw));
    // QTextBrowserのサイズを確定させるトリック。
    QResizeEvent e(size(),size());
    resizeEvent(&e);
}

qlonglong SaoriViewEntry::id()
{
    return m_id;
}

void SaoriViewEntry::resizeEvent(QResizeEvent *e)
{
    QTextBrowser::resizeEvent(e);
    document()->setTextWidth(qreal(e->size().width()));
    setMinimumHeight(document()->size().height() + 5);
}

const QString SaoriViewEntry::designedText(bool cw)
{
    QString result;
    result += "<head><style type=\"text/css\">";
    result += "a {color:" + palette().color(QPalette::Text).name() + ";}";
    if (cw) {
        result += "div.content *{background-color:";
        result += palette().color(QPalette::Text).name();
        result += ";}";
    }
    result += "</style><link rel=\"stylesheet\" type=\"text/css\" href=\":/css/saoristyle.css\" />";
    result += "</head>";
    result += "<body>";
    result += imageReplacer();
    result += "</body>";
    return result;
}

const QString SaoriViewEntry::imageReplacer()
{
    QString result = m_original;
    for (auto k:m_urlmap.keys()) {
        result.replace(QString("<img(" + k + ")"),
                       QString("<img src=\"img:" + m_urlmap[k] + "\""));
    }
    return result;
}

void SaoriViewEntry::imageResizer(const QString type, QImage &image)
{
    QStringList c;
    c << "avatar" << "mavatar" << "media" << "nsfwmedia" << "icon";
    switch (c.indexOf(type)) {
    case 0:
        image = roundedImage(image,10).scaled(64,64,Qt::KeepAspectRatio,Qt::SmoothTransformation);
        break;
    case 1:
        image = roundedImage(image,10).scaled(32,32,Qt::KeepAspectRatio,Qt::SmoothTransformation);
        break;
    case 2:
        image = roundedImage(image,20).scaledToWidth(200,Qt::SmoothTransformation);
        break;
    case 3:
        if (SaoriApplication::saori()->setting()->value(SAORI_SETTING_NSFWBLUR,SAORI_SETTING_NSFWBLUR_DEFAULT).toBool())
            image = image.scaledToWidth(10,Qt::SmoothTransformation);
        image = image.scaledToWidth(200,Qt::SmoothTransformation);
        image = roundedImage(image,20);
        break;
    case 4:
        image = image.scaled(24,24,Qt::KeepAspectRatio,Qt::SmoothTransformation);
        break;
    default:
        break;
    }
    return;
}

QImage SaoriViewEntry::roundedImage(QImage &image, int r)
{
    QPainter painter;
    QPainterPath p;
    QImage i;
    i = QImage(image.width(),image.height(),QImage::Format_RGBA8888);
    i.fill(QColor(0,0,0,0));
    p.addRoundedRect(0,0,image.width(),image.height(),image.width() / r,image.width() / r);
    painter.begin(&i);
    painter.fillPath(p,QBrush(image));
    painter.end();
    return i;
}

void SaoriViewEntry::downloaded(const QUrl url)
{
    setContent(m_original,m_cw);
    for (auto i = m_urlmap.begin();i != m_urlmap.end();i ++) {
        if (i.key().mid(i.key().indexOf(':') + 1, -1) == url.toString()) {
            setContent(m_original,m_cw);
            break;
        }
    }

    for(auto i:m_urlmap) {
        if (i == SAORI_ICONS_LOADING) return;
    }

    disconnect(SaoriApplication::saori()->cache(),&SaoriCache::downloaded,this,&SaoriViewEntry::downloaded);
}