/*
    Copyright (c) 2008 Louai Al-Khanji

    This file is part of Safra.

    Safra is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 2 as published
    by the Free Software Foundation.

    Safra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Safra; see the file COPYING. If not, see
    <http://www.gnu.org/licenses/>.
*/

#include <QMouseEvent>
#include <KUrl>
#include <QUrl>

#include "webview.h"

WebView::WebView(QWidget* parent) : QWebView(parent)
{
    connect(page(), SIGNAL(linkHovered(QString, QString, QString)),
            this, SIGNAL(statusBarMessage(QString)));
    connect(page(), SIGNAL(linkHovered(QString, QString, QString)),
             this, SLOT(updateHoveredLink(QString)));
}

void WebView::load(const QUrl& link)
{
    KUrl url = massageUrl(link);
    QWebView::load(url);
}

void WebView::mousePressEvent(QMouseEvent* event)
{
    if (event->button() == Qt::MidButton)
    {
        emit middleClicked(m_hoveredLink);
        return;
    }

    QWebView::mousePressEvent(event);
}

void WebView::paintEvent(QPaintEvent* event)
{
    QWebView::paintEvent(event);
}

void WebView::updateHoveredLink(const QString& link)
{
    m_hoveredLink = link;
}

KUrl WebView::massageUrl(const QUrl& url)
{
    KUrl kurl(url);
    if (kurl.scheme().isEmpty()) {
        if (kurl.isRelative()) {
            kurl = KUrl("//").resolved(kurl);
        }
        kurl.setScheme("http");
    }
    return kurl;
}

#include "webview.moc"
