/* This file is part of the KDE project
   Copyright (C) 2001 Andrea Rizzi <rizzi@kde.org>
	              Ulrich Kuettler <ulrich.kuettler@mailbox.tu-dresden.de>

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

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/

class KPrinter;

#include <tqpainter.h>
#include <tqpopupmenu.h>
#include <tqtextedit.h>
#include <tqtimer.h>

#include <tdeaction.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <tdelocale.h>
#include <kstdaction.h>
#include <ktip.h>
//#include <tdeglobal.h>

#include <kformulacontainer.h>
#include <kformuladocument.h>

#include "formulastring.h"
#include "fsparser.h"
#include "kfconfig.h"
#include "kformula_doc.h"
#include "kformula_factory.h"
#include "kformula_view.h"
#include "kformula_view_iface.h"
#include "kformulawidget.h"


bool KFormulaPartView::first_window = true;

KFormulaPartView::KFormulaPartView(KFormulaDoc* _doc, TQWidget* _parent, const char* _name)
        : KoView( _doc, _parent, _name ), m_pDoc(_doc)
{
    setInstance(KFormulaFactory::global());
    if ( !_doc->isReadWrite() )
        setXMLFile("kformula_readonly.rc");
    else
        setXMLFile("kformula.rc");

    m_dcop = 0;
    dcopObject(); // build it

    scrollview = new TQScrollView(this, "scrollview");
    formulaWidget = new KFormulaWidget(_doc->getFormula(), scrollview->viewport(), "formulaWidget");
    scrollview->addChild(formulaWidget);

    scrollview->viewport()->setFocusProxy( scrollview );
    scrollview->viewport()->setFocusPolicy( TQ_WheelFocus );
    scrollview->setFocusPolicy( TQ_NoFocus );
    formulaWidget->setFocus();

    // Nice parts start in read only mode.
    formulaWidget->setReadOnly(true);

    KFormula::Container* formula = m_pDoc->getFormula();
    KFormula::Document* document = m_pDoc->getDocument();

    // copy&paste
    cutAction   = KStdAction::cut(document->wrapper(), TQT_SLOT(cut()), actionCollection());
    copyAction  = KStdAction::copy(document->wrapper(), TQT_SLOT(copy()), actionCollection());
    pasteAction = KStdAction::paste(document->wrapper(), TQT_SLOT(paste()), actionCollection());
    cutAction->setEnabled(false);
    copyAction->setEnabled(false);

    // tip of the day
    KStdAction::tipOfDay( TQT_TQOBJECT(this), TQT_SLOT( slotShowTip() ), actionCollection() );

    // elements
    addBracketAction      = document->wrapper()->getAddBracketAction();
    addFractionAction     = document->wrapper()->getAddFractionAction();
    addRootAction         = document->wrapper()->getAddRootAction();
    addSumAction          = document->wrapper()->getAddSumAction();
    addProductAction      = document->wrapper()->getAddProductAction();
    addIntegralAction     = document->wrapper()->getAddIntegralAction();
    addMatrixAction       = document->wrapper()->getAddMatrixAction();
    addUpperLeftAction    = document->wrapper()->getAddUpperLeftAction();
    addLowerLeftAction    = document->wrapper()->getAddLowerLeftAction();
    addUpperRightAction   = document->wrapper()->getAddUpperRightAction();
    addLowerRightAction   = document->wrapper()->getAddLowerRightAction();
    addGenericUpperAction = document->wrapper()->getAddGenericUpperAction();
    addGenericLowerAction = document->wrapper()->getAddGenericLowerAction();
    removeEnclosingAction = document->wrapper()->getRemoveEnclosingAction();

    (void) KStdAction::selectAll(TQT_TQOBJECT(formulaWidget), TQT_SLOT(slotSelectAll()), actionCollection());

    //------------------------ Settings menu
    KStdAction::preferences( TQT_TQOBJECT(this), TQT_SLOT(configure()), actionCollection(), "configure" );

    // font stuff
//     TDEFontAction* actionElement_Text_Font = new TDEFontAction(i18n( "Font Family" ),0,
//                                               actionCollection(),"textfont");
//     connect( actionElement_Text_Font, TQT_SIGNAL( activated( const TQString& ) ), TQT_TQOBJECT(this), TQT_SLOT( fontSelected( const TQString& ) ) );

    TDEFontSizeAction* actionTextSize = new TDEFontSizeAction(i18n( "Size" ),0,
                                                          actionCollection(),"formula_textsize");
    actionTextSize->setFontSize( m_pDoc->getFormula()->fontSize() );

    connect( actionTextSize, TQT_SIGNAL( fontSizeChanged( int ) ), TQT_TQOBJECT(this), TQT_SLOT( sizeSelected( int ) ) );
    connect( formula, TQT_SIGNAL( baseSizeChanged( int ) ), actionTextSize, TQT_SLOT( setFontSize( int ) ) );

//     TDEToggleAction* actionElement_Text_Bold = new TDEToggleAction(i18n( "Bold" ),
//                                                   "bold",
//                                                   0,
//                                                   actionCollection(),"textbold");
//     connect( actionElement_Text_Bold, TQT_SIGNAL( toggled( bool ) ), TQT_TQOBJECT(this), TQT_SLOT( bold( bool ) ) );

//     TDEToggleAction* actionElement_Text_Italic = new TDEToggleAction(i18n( "Italic" ),
//                                                    "italic",
//                                                    0,
//                                                    actionCollection(),"textitalic");
//     connect( actionElement_Text_Italic, TQT_SIGNAL( toggled( bool ) ), TQT_TQOBJECT(this), TQT_SLOT( italic( bool ) ) );

//     TDEToggleAction* actionElement_Text_Under = new TDEToggleAction(i18n( "Underlined" ),
//                                                   "underl",
//                                                   0,
//                                                   actionCollection(),"textunder");
//     connect(actionElement_Text_Under, TQT_SIGNAL( toggled( bool ) ), TQT_TQOBJECT(this), TQT_SLOT( underline( bool ) ) );


    formulaStringAction = new TDEAction( i18n( "Edit Formula String..." ),
                                       0,
                                       TQT_TQOBJECT(this), TQT_SLOT( formulaString() ),
                                       actionCollection(), "formula_formulastring" );
    // notify on cursor change
    connect(formulaWidget, TQT_SIGNAL(cursorChanged(bool, bool)),
            TQT_TQOBJECT(this), TQT_SLOT(cursorChanged(bool, bool)));

    connect( formula, TQT_SIGNAL( statusMsg( const TQString& ) ),
             TQT_TQOBJECT(this), TQT_SLOT( slotActionStatusText( const TQString& ) ) );

    if ( !_doc->isEmbedded() && first_window ) {
        TQTimer::singleShot( 200, TQT_TQOBJECT(this), TQT_SLOT(slotShowTipOnStart()) );
        first_window = false;
    }
}


KFormulaPartView::~KFormulaPartView()
{
    delete m_dcop;
}

DCOPObject* KFormulaPartView::dcopObject()
{
    if ( !m_dcop )
	m_dcop = new KformulaViewIface( this );

    return m_dcop;
}


void KFormulaPartView::focusInEvent(TQFocusEvent*)
{
    formulaWidget->setFocus();
}

void KFormulaPartView::updateReadWrite(bool readwrite)
{
    formulaWidget->setReadOnly(!readwrite);
    setEnabled(readwrite);
}

void KFormulaPartView::slotShowTipOnStart() {
    KTipDialog::showTip( this );
}

void KFormulaPartView::slotShowTip() {
    KTipDialog::showTip( this, TQString(), true );
}


void KFormulaPartView::setEnabled(bool enabled)
{
    addBracketAction->setEnabled(enabled);
    addFractionAction->setEnabled(enabled);
    addRootAction->setEnabled(enabled);
    addSumAction->setEnabled(enabled);
    addIntegralAction->setEnabled(enabled);
    addMatrixAction->setEnabled(enabled);
    addUpperLeftAction->setEnabled(enabled);
    addLowerLeftAction->setEnabled(enabled);
    addUpperRightAction->setEnabled(enabled);
    addLowerRightAction->setEnabled(enabled);
    addGenericUpperAction->setEnabled(enabled);
    addGenericLowerAction->setEnabled(enabled);
    removeEnclosingAction->setEnabled(enabled);
}

void KFormulaPartView::resizeEvent( TQResizeEvent * )
{
    scrollview->setGeometry(0, 0, width(), height());
}


void KFormulaPartView::setupPrinter(KPrinter&)
{
}

void KFormulaPartView::print(KPrinter& printer)
{
    m_pDoc->getFormula()->print(printer);
}

const KFormula::View* KFormulaPartView::formulaView() const { return formulaWidget->view(); }
KFormula::View* KFormulaPartView::formulaView() { return formulaWidget->view(); }

void KFormulaPartView::cursorChanged(bool visible, bool selecting)
{
    cutAction->setEnabled(visible && selecting);
    copyAction->setEnabled(visible && selecting);

    removeEnclosingAction->setEnabled(!selecting);

    if (visible) {
        int x = formulaWidget->getCursorPoint().x();
        int y = formulaWidget->getCursorPoint().y();
        scrollview->ensureVisible(x, y);
    }

    KFormula::Document* doc = document()->getDocument();
    doc->wrapper()->getFormatBoldAction()->setEnabled( selecting );
    doc->wrapper()->getFormatItalicAction()->setEnabled( selecting );
    doc->wrapper()->getFontFamilyAction()->setEnabled( selecting );
    if ( !selecting ) {
        doc->wrapper()->getFormatBoldAction()->setChecked( false );
        doc->wrapper()->getFormatItalicAction()->setChecked( false );
        doc->wrapper()->getFontFamilyAction()->setCurrentItem( 0 );
    }
}

void KFormulaPartView::formulaString()
{
    FormulaString dia( this );
    dia.textWidget->setText( document()->getFormula()->formulaString() );
    if ( dia.exec() ) {
        // How lovely.
    }
}

void KFormulaPartView::sizeSelected( int size )
{
    document()->getFormula()->setFontSize( size );
    formulaWidget->setFocus();
}

TQStringList KFormulaPartView::readFormulaString( TQString text )
{
    FormulaStringParser parser( document()->getDocument()->getSymbolTable(), text );
    TQDomDocument formula = parser.parse();
    TQStringList errorList = parser.errorList();
    //if ( errorList.count() == 0 ) {
        formulaView()->slotSelectAll();
        document()->getFormula()->paste( formula, i18n( "Read Formula String" ) );
        //}
    return errorList;
}

void KFormulaPartView::configure()
{
    KFConfig configDia( this );
    configDia.exec();
}

#include "kformula_view.moc"