/***************************************************************************
 *   Copyright (C) 2004 by Teemu Rytilahti                                 *
 *   teemu.rytilahti@kde-fi.org                                            *
 *                                                                         *
 *   Licensed under GPL.                                                   *
 ***************************************************************************/

#include <tdeaction.h>
#include <tdeapplication.h>
#include <tdehtmlview.h>
#include <kiconloader.h>
#include <tdelocale.h>
#include <tdepopupmenu.h>

#include <tqclipboard.h>
#include <tqfile.h>
#include <tqpaintdevicemetrics.h>

#include "viewer.h"
#include "klamav_run.h"
//#include "akregatorconfig.h"

using namespace KlamAV;

Viewer::Viewer(TQWidget *parent, const char *name)
    : TDEHTMLPart(parent, name), m_url(0)
{
    setZoomFactor(100);
    setJScriptEnabled(true);
    setJavaEnabled(true);
    setMetaRefreshEnabled(true);
    setPluginsEnabled(true);
    setDNDEnabled(true);
    setAutoloadImages(true);
    setStatusMessagesEnabled(true);

    // change the cursor when loading stuff...
    connect( this, TQ_SIGNAL(started(TDEIO::Job *)),
             this, TQ_SLOT(slotStarted(TDEIO::Job *)));
    connect( this, TQ_SIGNAL(completed()),
             this, TQ_SLOT(slotCompleted()));

    connect( browserExtension(), TQ_SIGNAL(openURLRequestDelayed(const KURL&, const KParts::URLArgs&)), this, TQ_SLOT(slotOpenURLRequest(const KURL&, const KParts::URLArgs& )) );

    connect( browserExtension(),

TQ_SIGNAL(popupMenu (KXMLGUIClient*, const TQPoint&, const KURL&, const
    KParts::URLArgs&, KParts::BrowserExtension::PopupFlags, mode_t)), this, TQ_SLOT(slotPopupMenu(KXMLGUIClient*, const TQPoint&, const KURL&, const
    KParts::URLArgs&, KParts::BrowserExtension::PopupFlags, mode_t)));

    KStdAction::print(this, TQ_SLOT(slotPrint()), actionCollection(), "viewer_print");
    KStdAction::copy(this, TQ_SLOT(slotCopy()), actionCollection(), "viewer_copy");
    
    new TDEAction( i18n("&Increase Font Sizes"), "viewmag+", "Ctrl+Plus", this, TQ_SLOT(slotZoomIn()), actionCollection(), "incFontSizes" );
    new TDEAction( i18n("&Decrease Font Sizes"), "viewmag-", "Ctrl+Minus", this, TQ_SLOT(slotZoomOut()), actionCollection(), "decFontSizes" );

    connect(this, TQ_SIGNAL(selectionChanged()), this, TQ_SLOT(slotSelectionChanged()));

    new TDEAction(i18n("Copy &Link Address"), "", 0,
                                 this, TQ_SLOT(slotCopyLinkAddress()),
                                 actionCollection(), "copylinkaddress");
}

bool Viewer::openURL(const KURL &url)
{
    new KlamAV::BrowserRun(this, (TQWidget*)parent(), this, url, KParts::URLArgs());
    emit started(0);
    return true;
}

/* borrowed from Konqueror */
TQString Viewer::loadFile( const TQString& file ) {
	TQString res;
	if( file.isEmpty() )
		return res;

	TQFile f(file);

	if( !f.open(IO_ReadOnly) )
		return res;

	TQTextStream t(&f);
	res = t.read();

	return res;
}

bool Viewer::closeURL()
{
    emit browserExtension()->loadingProgress(-1);
    emit canceled(TQString::null);
    return TDEHTMLPart::closeURL();
}

int Viewer::pointsToPixel(int pointSize) const
{
    const TQPaintDeviceMetrics metrics(view());
    return ( pointSize * metrics.logicalDpiY() + 36 ) / 72 ;
}

void Viewer::displayInExternalBrowser(const KURL &url, const TQString &mimetype)
{
   if (!url.isValid()) return;
/*   if (Settings::externalBrowserUseKdeDefault())
   {*/
       if (mimetype.isEmpty()) 
           kapp->invokeBrowser(url.url(), "0");
       else
           KRun::runURL(url, mimetype, false, false);
/*   }
   else
   {
       TQString cmd = Settings::externalBrowserCustomCommand();
       TQString urlStr = url.url();
       cmd.replace(TQRegExp("%u"), urlStr);
       TDEProcess *proc = new TDEProcess;
       TQStringList cmdAndArgs = KShell::splitArgs(cmd);
       *proc << cmdAndArgs;
       proc->start(TDEProcess::DontCare);
       delete proc;
   }*/
}


void Viewer::slotOpenURLRequest(const KURL& url, const KParts::URLArgs& args)
{
    m_url = url;
    if (args.frameName == "_blank") // apparently this indicates that the MMB was pressed...
    {
/*        switch (Settings::mMBBehaviour())
        {
            case Settings::EnumMMBBehaviour::OpenInExternalBrowser:
                slotOpenLinkInBrowser();
                break;
            case Settings::EnumMMBBehaviour::OpenInBackground:
                slotOpenLinkInBackgroundTab();
                break;
            default:*/
                slotOpenLinkInForegroundTab();
/*                break;
        }*/
    }
    else // LMB:
    {
/*        switch (Settings::lMBBehaviour())
        {
            case Settings::EnumLMBBehaviour::OpenInExternalBrowser:
                slotOpenLinkInBrowser();
                break;
            case Settings::EnumLMBBehaviour::OpenInBackground:
                slotOpenLinkInBackgroundTab();
                break;
            default:*/
                slotOpenLinkInForegroundTab();
/*                break;
        }*/
    }
}

void Viewer::slotPopupMenu(KXMLGUIClient*, const TQPoint& p, const KURL& kurl, const KParts::URLArgs&, KParts::BrowserExtension::PopupFlags, mode_t)
{
   TQString url = kurl.url();
   if(this->url() == url) return;
   m_url = url;
   TDEPopupMenu popup;
   
   if (!url.isEmpty())
   {
        popup.insertItem(SmallIcon("tab_new"), i18n("Open Link in New &Tab"), this, TQ_SLOT(slotOpenLinkInForegroundTab()));
        popup.insertItem(SmallIcon("window-new"), i18n("Open Link in External &Browser"), this, TQ_SLOT(slotOpenLinkInBrowser()));
        action("copylinkaddress")->plug(&popup);
   }
   else
   {
       action("viewer_copy")->plug(&popup);
       popup.insertSeparator();
       action("viewer_print")->plug(&popup);
       TDEAction *ac = action("setEncoding");
       if (ac)
            ac->plug(&popup);
   }
   popup.exec(p);
}

// taken from KDevelop
void Viewer::slotCopy()
{
    TQString text = selectedText();
    text.replace( TQChar( 0xa0 ), ' ' );
    TQClipboard *cb = TQApplication::clipboard();
    disconnect( cb, TQ_SIGNAL( selectionChanged() ), this, TQ_SLOT( slotClearSelection() ) );
    cb->setText(text);
    connect( cb, TQ_SIGNAL( selectionChanged() ), this, TQ_SLOT( slotClearSelection() ) );
}

void Viewer::slotCopyLinkAddress()
{
   if(m_url.isEmpty()) return;
   TQClipboard *cb = TQApplication::clipboard();
   cb->setText(m_url.prettyURL(), TQClipboard::Clipboard);
   cb->setText(m_url.prettyURL(), TQClipboard::Selection);
}

void Viewer::slotSelectionChanged()
{
    action("viewer_copy")->setEnabled(!selectedText().isEmpty());
}

void Viewer::slotOpenLinkInternal()
{
   openURL(m_url);
}

void Viewer::slotOpenLinkInForegroundTab()
{
    emit urlClicked(m_url, false);
}

void Viewer::slotOpenLinkInBackgroundTab()
{
    emit urlClicked(m_url, true);
}

void Viewer::slotOpenLinkInBrowser()
{
    kdDebug() << "display external" << endl;
    displayInExternalBrowser(m_url, TQString::null);
}

void Viewer::slotStarted(TDEIO::Job *)
{
   widget()->setCursor( waitCursor );
}

void Viewer::slotCompleted()
{
   widget()->unsetCursor();
}

void Viewer::slotScrollUp()
{
    view()->scrollBy(0,-10);
}

void Viewer::slotScrollDown()
{
    view()->scrollBy(0,10);
}

void Viewer::slotZoomIn()
{
    int zf = zoomFactor();
    if (zf < 100)
    {
        zf = zf - (zf % 20) + 20;
        setZoomFactor(zf);
    }
    else
    {
        zf = zf - (zf % 50) + 50;
        setZoomFactor(zf < 300 ? zf : 300);
    }
}

void Viewer::slotZoomOut()
{
    int zf = zoomFactor();
    if (zf <= 100)
    {
        zf = zf - (zf % 20) - 20;
        setZoomFactor(zf > 20 ? zf : 20);
    }
    else
    {
        zf = zf - (zf % 50) - 50;
        setZoomFactor(zf);
    }
}

void Viewer::slotSetZoomFactor(int percent)
{
    setZoomFactor(percent);
}

// some code taken from KDevelop (lib/widgets/kdevhtmlpart.cpp)
void Viewer::slotPrint( )
{
    view()->print();
}


void Viewer::setSafeMode()
{
    setJScriptEnabled(false);
    setJavaEnabled(false);
    setMetaRefreshEnabled(false);
    setPluginsEnabled(false);
    setDNDEnabled(true);
    setAutoloadImages(true);
    setStatusMessagesEnabled(false);
}

#include "viewer.moc"
