/* ****************************************************************************
  This file is part of KBabel

  Copyright (C) 1999-2000 by Matthias Kiefer
                            <matthias.kiefer@gmx.de>
		2001-2003 by Stanislav Visnovsky
			    <visnovsky@kde.org>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program 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 this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

**************************************************************************** */
#include "klisteditor.h"
#include "toolselectionwidget.h"
#include "prefwidgets.h"
#include "resources.h"
#include "kbabeldictbox.h"
#include "toolaction.h"

#include <kcombobox.h>
#include <kdatatool.h>
#include <klocale.h>
#include <kdialog.h>
#include <kfiledialog.h>
#include <knuminput.h>
#include <kmessagebox.h>
#include <klineedit.h> 
#include <kurlcompletion.h>
#include <kfontdialog.h>
#include <kcolorbutton.h>
#include <kparts/componentfactory.h>
#include <kregexpeditorinterface.h>
#include <ksconfig.h>
#include <kurldrag.h>
#include <kurlrequester.h>

#include <qlayout.h>
#include <qobjectlist.h>
#include <qlabel.h>
#include <qvbox.h>
#include <qlineedit.h>
#include <qcheckbox.h>
#include <qgroupbox.h>
#include <qhbuttongroup.h>
#include <qvbuttongroup.h>
#include <qpushbutton.h>
#include <qcombobox.h>
#include <qradiobutton.h>
#include <qspinbox.h>
#include <qtextcodec.h>
#include <qwhatsthis.h>

using namespace KBabel;

static QSize sizeHintForWidget(const QWidget* widget)
{
  //
  // The size is computed by adding the sizeHint().height() of all
  // widget children and taking the width of the widest child and adding
  // layout()->margin() and layout()->spacing()
  //

  QSize size;

  int numChild = 0;
  QObjectList *l = (QObjectList*)(widget->children());

  for( uint i=0; i < l->count(); i++ )
  {
    QObject *o = l->at(i);
    if( o->isWidgetType() )
    {
      numChild += 1;
      QWidget *w=((QWidget*)o);

      QSize s = w->sizeHint();
      if( s.isEmpty() == true )
      {
          s = QSize( 50, 100 ); // Default size
      }
      size.setHeight( size.height() + s.height() );
      if( s.width() > size.width() ) { size.setWidth( s.width() ); }
    }
  }

  if( numChild > 0 )
  {
    size.setHeight( size.height() + widget->layout()->spacing()*(numChild-1) );
    size += QSize( widget->layout()->margin()*2, widget->layout()->margin()*2 + 1 );
  }
  else
  {
    size = QSize( 1, 1 );
  }

  return( size );
}




SavePreferences::SavePreferences(QWidget *parent)
    :  KTabCtl(parent)
{
    QWidget* page = new QWidget(this);
    QVBoxLayout* layout=new QVBoxLayout(page);
    layout->setSpacing(KDialog::spacingHint());
    layout->setMargin(KDialog::marginHint());

    QGroupBox* box=new QGroupBox(1,Qt::Horizontal,page);
    layout->addWidget(box);

    box->setMargin(KDialog::marginHint());
    _updateButton = new QCheckBox(i18n("&Update header when saving"),box);
    _descriptionButton = new QCheckBox(i18n("Update &description comment when saving"),box);
    _autoCheckButton = new QCheckBox(i18n("Chec&k syntax of file when saving"),box);
    _saveObsoleteButton = new QCheckBox(i18n("Save &obsolete entries"),box);
    
    QGroupBox* descBox=new QGroupBox(1,Qt::Horizontal,i18n("De&scription"),page);
    layout->addWidget(descBox);
    
    descBox->setMargin(KDialog::marginHint());
    _descriptionEdit = new QLineEdit(descBox);

    QGroupBox* encodingBox = new QGroupBox(1,Qt::Horizontal,i18n("Encoding")
                                  ,page);
    encodingBox->setMargin(KDialog::marginHint());
    layout->addWidget(encodingBox);
    QHBox *b = new QHBox(encodingBox);

    QLabel* tempLabel=new QLabel(i18n("Default:"),b);
    _encodingBox = new QComboBox(b);
    b->setStretchFactor(_encodingBox,2);
    b->setSpacing(KDialog::spacingHint());

    QString defaultName=charsetString(Locale);
    defaultName+=" "+i18n("(default)");
    QString utf8Name=charsetString(UTF8);
    QString utf16Name=charsetString(UTF16);

    _encodingBox->insertItem(defaultName,(int)Locale);
    _encodingBox->insertItem(utf8Name,(int)UTF8);

    // KBabel seems to crash somehow, when saving in utf16, so
    // it's better to disable this, since it is useless anyway
    // at the moment
    //_encodingBox->insertItem(utf16Name,(int)UTF16);

    tempLabel->setBuddy(_encodingBox);

    _oldEncodingButton = new QCheckBox(i18n("Kee&p the encoding of the file")
                     ,encodingBox);

    _autoSaveBox = new QGroupBox( 1, Qt::Horizontal, i18n( "Automatic Saving" ), page );
    _autoSaveBox->setMargin( KDialog::marginHint( ) );
    layout->addWidget( _autoSaveBox );
    _autoSaveDelay = new KIntNumInput( _autoSaveBox );
    _autoSaveDelay->setRange( 0, 60 );
    _autoSaveDelay->setSuffix( i18n( "Short for minutes", " min" ) );
    _autoSaveDelay->setSpecialValueText( i18n( "No autosave" ) );

    layout->addStretch(1);
    page->setMinimumSize(sizeHintForWidget(page));
    addTab(page, i18n("&General"));
    
    page = new QWidget(this);
    layout=new QVBoxLayout(page);
    layout->setSpacing(KDialog::spacingHint());
    layout->setMargin(KDialog::marginHint());

    QGroupBox* gridBox = new QGroupBox(2,Qt::Horizontal,i18n("Fields to Update"),page);
    layout->addWidget(gridBox);
    gridBox->setMargin(KDialog::marginHint());

    _revisionButton = new QCheckBox(i18n("Re&vision-Date"),gridBox);
    _lastButton = new QCheckBox(i18n("Last-&Translator"),gridBox);
    _languageButton = new QCheckBox(i18n("&Language"),gridBox);
    _charsetButton = new QCheckBox(i18n("Char&set"),gridBox);
    _encodingButton = new QCheckBox(i18n("&Encoding"),gridBox);
    _projectButton = new QCheckBox(i18n("Pro&ject"),gridBox);

    QGroupBox* dateBox = new QButtonGroup(2,Qt::Horizontal,i18n("Format of Revision-Date"),page);
    layout->addWidget(dateBox);
    box->setMargin(KDialog::marginHint());

    _defaultDateButton = new QRadioButton( i18n("De&fault date format"),dateBox );
    _localDateButton = new QRadioButton( i18n("Local date fo&rmat"),dateBox );
    _customDateButton = new QRadioButton( i18n("Custo&m date format:"),dateBox );
    _dateFormatEdit = new QLineEdit(dateBox);
    _dateFormatEdit->setEnabled(false);

    connect( _customDateButton, SIGNAL(toggled(bool)), this, SLOT( customDateActivated(bool) ) );

    QGroupBox* projectBox = new QGroupBox(1,Qt::Horizontal,i18n("Project String")
                                  ,page);
    projectBox->setMargin(KDialog::marginHint());
    layout->addWidget(projectBox);
    b = new QHBox(projectBox);

    tempLabel=new QLabel(i18n("Project-Id:"),b);
    _projectEdit = new QLineEdit(b);
    b->setStretchFactor(_projectEdit,2);
    b->setSpacing(KDialog::spacingHint());
    tempLabel->setBuddy(_projectEdit);
    
    layout->addStretch(1);
    page->setMinimumSize(sizeHintForWidget(page));
    addTab(page, i18n("&Header"));
    
    page = new QWidget(this);
    layout=new QVBoxLayout(page);
    layout->setSpacing(KDialog::spacingHint());
    layout->setMargin(KDialog::marginHint());

    QGroupBox* translatorCopyrightBox = new QGroupBox(1,Qt::Horizontal, page);
    translatorCopyrightBox->setMargin(KDialog::marginHint());
    _translatorCopyrightButton = 
	new QCheckBox(i18n("Update &translator copyright"),translatorCopyrightBox);
    layout->addWidget(translatorCopyrightBox);

    QGroupBox* fsfBox=new QButtonGroup(1,Qt::Horizontal,i18n("Free Software Foundation Copyright"),page);
    layout->addWidget(fsfBox);

    fsfBox->setMargin(KDialog::marginHint());
    _removeFSFButton = new QRadioButton(i18n("&Remove copyright if empty"),fsfBox);
    _updateFSFButton = new QRadioButton(i18n("&Update copyright"),fsfBox);
    _nochangeFSFButton = new QRadioButton(i18n("Do &not change"),fsfBox);

    layout->addStretch(1);
    page->setMinimumSize(sizeHintForWidget(page));
    addTab(page, i18n("Cop&yright"));

    QWhatsThis::add(_updateButton,
        i18n("<qt><p><b>Update Header</b></p>\n"
             "<p>Check this button to update the header "
             "information of the file "
             "every time it is saved.</p>\n"
             "<p>The header normally keeps information about "
             "the date and time the file was last\n"
             "updated, the last translator etc.</p>\n"
             "<p>You can choose which information you want to update from the checkboxes below.\n"
             "Fields that do not exist are added to the header.\n"
             "If you want to add additional fields to the header, you can edit the header manually by choosing\n"
             "<b>Edit->Edit Header</b> in the editor window.</p></qt>"));

    QWhatsThis::add(gridBox,i18n("<qt><p><b>Fields to update</b></p>\n"
 "<p>Choose which fields in the header you want to have updated when saving.\n"
 "If a field does not exist, it is appended to the header.</p>\n"
 "<p>If you want to add other information to the header, you have to edit the header manually\n"
 "by choosing <b>Edit->Edit Header</b> in the editor window.</p>\n"
 "<p>Deactivate <b>Update Header</b> above if you don't want to have the header\n"
 "updated when saving.</p></qt>"));

    QWhatsThis::add(encodingBox,i18n("<qt><p><b>Encoding</b></p>"
"<p>Choose how to encode characters when saving to a file. If you are unsure "
"what encoding to use, please ask your translation coordinator.</p>"
"<ul><li><b>%1</b>: this is the encoding that fits the character "
"set of your system language.</li>"
"<li><b>%2</b>: uses unicode (UTF-8) encoding.</li>"
"<li><b>%3</b>: uses unicode (UTF-16) encoding."
"This is not recommended at the moment because gettext might have some trouble reading this.</li></ul></qt>").arg(defaultName).arg(utf8Name).arg(utf16Name) );


    QWhatsThis::add(_oldEncodingButton
        ,i18n("<qt><p><b>Keep the encoding of the file</b></p>"
        "<p>If this option is activated, files are always saved in the "
        "same encoding as they were read in. Files without charset "
        "information in the header (e.g. POT files) are saved in the "
        "encoding set above.</p></qt>"));

    QWhatsThis::add(_autoCheckButton,i18n("<qt><p><b>Check syntax of file when saving</b></p>\n"
"<p>Check this to automatically check syntax of file with \"msgfmt --statistics\"\n"
"when saving a file. You will only get a message, if an error occurred.</p></qt>"));

    QWhatsThis::add(_saveObsoleteButton,i18n("<qt><p><b>Save obsolete entries</b></p>\n"
"<p>If this option is activated, obsolete entries found when the file was open\n"
"will be saved back to the file. Obsolete entries are marked by #~ and are\n"
"created when the msgmerge does not need the translation anymore.\n"
"If the text will appear again, the obsolete entries will be activated again.\n"
"The main drawback is the size of the saved file.</p></qt>"));


    QWhatsThis::add(dateBox, i18n("<qt><p><b>Format of Revision-Date</b></p>"
"<p>Choose in which format the date and time of the header field\n"
"<i>PO-Revision-Date</i> is saved: <ul>\n"
"<li><b>Default</b> is the format normally used in PO files.</li>\n"
"<li><b>Local</b> is the format specific to your country.\n"
"It can be configured in KDE's Control Center.</li>\n"
"<li><b>Custom</b> lets you define your own format.</li></ul></p> "
"<p>For more information, see section <b>The Preferences Dialog</b> "
"in the online help.</p></qt>") );

    setMinimumSize(sizeHint());


    defaults();
}


void SavePreferences::setSettings(const SaveSettings& settings)
{
   _updateButton->setChecked(settings.autoUpdate);

   _lastButton->setChecked(settings.updateLastTranslator);
   _revisionButton->setChecked(settings.updateRevisionDate);
   _languageButton->setChecked(settings.updateLanguageTeam);
   _charsetButton->setChecked(settings.updateCharset);
   _encodingButton->setChecked(settings.updateEncoding);
   _projectButton->setChecked(settings.updateProject);

   _encodingBox->setCurrentItem((int)settings.encoding);
   _oldEncodingButton->setChecked(settings.useOldEncoding);

   _projectEdit->setText(settings.projectString);
   
   _descriptionButton->setChecked(settings.updateDescription);
   _descriptionEdit->setText(settings.descriptionString);
   _translatorCopyrightButton->setChecked(settings.updateTranslatorCopyright);
   
   switch(settings.FSFCopyright)
   {
      case Update:
         _updateFSFButton->setChecked(true);
         break;
      case Remove:
         _removeFSFButton->setChecked(true);
         break;
      case NoChange:
         _nochangeFSFButton->setChecked(true);
         break;
      case RemoveLine:
         break;
   }
   
   _autoCheckButton->setChecked(settings.autoSyntaxCheck);
   _saveObsoleteButton->setChecked(settings.saveObsolete);

   _dateFormatEdit->setText(settings.customDateFormat);

   switch(settings.dateFormat)
   {
      case Qt::ISODate:
         _defaultDateButton->setChecked(true);
         break;
      case Qt::LocalDate:
         _localDateButton->setChecked(true);
         break;
      case Qt::TextDate:
         _customDateButton->setChecked(true);
         break;
   }

   _autoSaveDelay->setValue( settings.autoSaveDelay );

}

void SavePreferences::mergeSettings(SaveSettings& settings) const
{
   settings.updateLastTranslator=_lastButton->isChecked();
   settings.updateRevisionDate=_revisionButton->isChecked();
   settings.updateLanguageTeam=_languageButton->isChecked();
   settings.updateCharset=_charsetButton->isChecked();
   settings.updateEncoding=_encodingButton->isChecked();
   settings.updateProject=_projectButton->isChecked();
   settings.autoUpdate=_updateButton->isChecked();

   settings.encoding=(FileEncoding)_encodingBox->currentItem();
   settings.useOldEncoding=_oldEncodingButton->isChecked();

   settings.projectString = _projectEdit->text();
   
   settings.autoSyntaxCheck = _autoCheckButton->isChecked();
   settings.saveObsolete = _saveObsoleteButton->isChecked();
   
   settings.updateDescription = _descriptionButton->isChecked();
   settings.descriptionString = _descriptionEdit->text();
   settings.updateTranslatorCopyright = _translatorCopyrightButton->isChecked();
   
   if(_removeFSFButton->isChecked())
   {
      settings.FSFCopyright=Remove;
   }
   else if(_updateFSFButton->isChecked())
   {
      settings.FSFCopyright=Update;
   }
   else
   {
      settings.FSFCopyright=NoChange;
   }

   settings.customDateFormat=_dateFormatEdit->text();

   if(_defaultDateButton->isChecked())
   {
      settings.dateFormat=Qt::ISODate;
   }
   else if(_localDateButton->isChecked())
   {
      settings.dateFormat=Qt::LocalDate;
   }
   else
   {
      settings.dateFormat=Qt::TextDate;
   }
   
   settings.autoSaveDelay = _autoSaveDelay->value( );
}

void SavePreferences::defaults()
{
   _updateButton->setChecked(KBabel::Defaults::Save::autoUpdate);

   _lastButton->setChecked(KBabel::Defaults::Save::updateLastTranslator);
   _revisionButton->setChecked(KBabel::Defaults::Save::updateRevisionDate);
   _languageButton->setChecked(KBabel::Defaults::Save::updateLanguageTeam);
   _charsetButton->setChecked(KBabel::Defaults::Save::updateCharset);
   _encodingButton->setChecked(KBabel::Defaults::Save::updateEncoding);
   _projectButton->setChecked(KBabel::Defaults::Save::updateProject);

   _encodingBox->setCurrentItem((int)KBabel::Defaults::Save::encoding);
   _oldEncodingButton->setChecked(KBabel::Defaults::Save::useOldEncoding);

   _projectEdit->setText(KBabel::Defaults::Save::projectString());
   
   _descriptionButton->setChecked(KBabel::Defaults::Save::updateDescription);
   _descriptionEdit->setText(KBabel::Defaults::Save::descriptionString());
   _translatorCopyrightButton->setChecked(KBabel::Defaults::Save::updateTranslatorCopyright);
   
   switch(KBabel::Defaults::Save::FSFCopyright)
   {
      case Update:
         _updateFSFButton->setChecked(true);
         break;
      case Remove:
         _removeFSFButton->setChecked(true);
         break;
      case NoChange:
         _nochangeFSFButton->setChecked(true);
         break;
      case RemoveLine:
         break;
   }
   
   _autoCheckButton->setChecked(KBabel::Defaults::Save::autoSyntaxCheck);
   _saveObsoleteButton->setChecked(KBabel::Defaults::Save::saveObsolete);

   _dateFormatEdit->setText(KBabel::Defaults::Save::customDateFormat());

   switch(KBabel::Defaults::Save::dateFormat)
   {
      case Qt::ISODate:
         _defaultDateButton->setChecked(true);
         break;
      case Qt::LocalDate:
         _localDateButton->setChecked(true);
         break;
      case Qt::TextDate:
         _customDateButton->setChecked(true);
         break;
   }

   _autoSaveDelay->setValue( KBabel::Defaults::Save::autoSaveDelay );
}


void SavePreferences::customDateActivated(bool on)
{
   _dateFormatEdit->setEnabled(on);
   _dateFormatEdit->setFocus();
}

void SavePreferences::setAutoSaveVisible( const bool on )
{
    if( on ) _autoSaveBox->show();
    else _autoSaveBox->hide();
}



IdentityPreferences::IdentityPreferences(QWidget* parent)
         : QWidget(parent)
{
    QWidget* page = this;
    QVBoxLayout* layout=new QVBoxLayout(page);
    layout->setSpacing(KDialog::spacingHint());
    layout->setMargin(KDialog::marginHint());

    QGroupBox* group = new QGroupBox(2,Qt::Horizontal,page);
    layout->addWidget(group);
    group->setMargin(KDialog::marginHint());

    QLabel* tempLabel=new QLabel(i18n("&Name:"),group);
    _nameEdit = new QLineEdit(group);
    tempLabel->setBuddy(_nameEdit);

    tempLabel=new QLabel(i18n("Localized na&me:"),group);
    _localNameEdit = new QLineEdit(group);
    tempLabel->setBuddy(_localNameEdit);

    tempLabel=new QLabel(i18n("E&mail:"),group);
    _mailEdit = new QLineEdit(group);
    tempLabel->setBuddy(_mailEdit);


    tempLabel=new QLabel(i18n("&Full language name:"),group);

    QHBox *hbox = new QHBox(group);
    hbox->setSpacing(KDialog::spacingHint());
    _langEdit = new QLineEdit(hbox);
    tempLabel->setBuddy(_langEdit);
    tempLabel=new QLabel(i18n("Lan&guage code:"),hbox);
    _langCodeEdit = new QLineEdit(hbox);
    tempLabel->setBuddy(_langCodeEdit);
    connect(_langCodeEdit,SIGNAL(textChanged(const QString&)), this
            , SLOT(checkTestPluralButton()));

    tempLabel=new QLabel(i18n("&Language mailing list:"),group);
    _listEdit = new QLineEdit(group);
    _listEdit->setMinimumSize(100,_listEdit->sizeHint().height());
    tempLabel->setBuddy(_listEdit);
 
    tempLabel=new QLabel(i18n("&Timezone:"), group);
    _timezoneEdit = new QLineEdit(group);
    _timezoneEdit->setMinimumSize(100,_timezoneEdit->sizeHint().height());
    tempLabel->setBuddy(_timezoneEdit);


    QString whatsThisMsg=i18n("<qt><p><b>Identity</b></p>\n"
"<p>Fill in information about you and your translation team.\n"
"This information is used when updating the header of a file.</p>\n"
"<p>You can find the options if and what fields in the header should be updated\n"
"on page <b>Save</b> in this dialog.</p></qt>");

    QWhatsThis::add(group,whatsThisMsg);



    group = new QGroupBox(1,Qt::Horizontal,page);
    layout->addWidget(group);
    group->setMargin(KDialog::marginHint());

    hbox = new QHBox(group);
    hbox->setSpacing(KDialog::spacingHint());

    QLabel *label = new QLabel(i18n("&Number of singular/plural forms:"), hbox);
    _pluralFormsBox = new QSpinBox(0,100,1,hbox);
    _pluralFormsBox->setSpecialValueText(
            i18n("automatic choose number of plural forms","Automatic"));
    label->setBuddy(_pluralFormsBox);
    connect(_pluralFormsBox,SIGNAL(valueChanged(int)), this
            , SLOT(checkTestPluralButton()));
    
    hbox->setStretchFactor(_pluralFormsBox,1);

    _testPluralButton = new QPushButton(i18n("Te&st"),hbox);
    _testPluralButton->setEnabled(false);
    connect(_testPluralButton, SIGNAL(clicked()), this
            , SLOT(testPluralForm()));

    QString msg=i18n("<qt><p><b>Number of singular/plural forms</b></p>\n"
            "<p><b>Note</b>: This option is KDE specific at the moment. "
            "If you are not translating a KDE application, you can safely "
            "ignore this option.</p>\n"
            "<p>Choose here how many singular and plural forms are used in "
            "your language. "
            "This number must correspond to the settings of your language "
            "team. "
            "If you are working with KDE >= 2.2 with support for the "
            "language you are translating to, set this option to "
            "<i>Automatic</i> and KBabel tries to get this information "
            "automatically from KDE. Use the <i>Test</i> button "
            "to test if it can find it out.</p></qt>");
    QWhatsThis::add(_pluralFormsBox,msg);
    QWhatsThis::add(_testPluralButton,msg);
    
    QVBox* vbox = new QVBox(group);
    vbox->setSpacing(KDialog::spacingHint());

    label = new QLabel(i18n("&GNU plural form header:"), vbox);
    
    hbox = new QHBox(vbox);
    hbox->setSpacing(KDialog::spacingHint());
    
    _gnuPluralFormHeaderEdit = new QLineEdit(hbox);
    label->setBuddy(_gnuPluralFormHeaderEdit);
    
    hbox->setStretchFactor(_gnuPluralFormHeaderEdit,1);

    _testGnuPluralFormButton = new QPushButton(i18n("&Lookup"),hbox);
    connect(_testGnuPluralFormButton, SIGNAL(clicked()), this
            , SLOT(lookupGnuPluralFormHeader()));

    _checkPluralArgumentBox = new QCheckBox( i18n("Re&quire plural form arguments in translation"), group );
    QWhatsThis::add(_checkPluralArgumentBox, 
	i18n("<qt><p><b>Require plural form arguments in translation</b></p>\n"
            "<p><b>Note</b>: This option is KDE specific at the moment. "
            "If you are not translating a KDE application, you can safely "
            "ignore this option.</p>\n"
	    "<p>If is this option enabled, the validation check will "
	    "require the %n argument to be present in the message.</p></qt>"));

    QWhatsThis::add(_gnuPluralFormHeaderEdit, 
	i18n("<qt><p><b>GNU plural form header</b></p>\n"
            "<p>Here you can fill a header entry for GNU plural form handling. "
            "If you leave the entry empty, the entry in the PO file will not be "
	    "changed or added.</p>\n"
	    "<p>KBabel can automatically try to determine value suggested by the "
	    "GNU gettext tools for currently set langauge. Just press the <b>Lookup</b> "
	    "button.</p></qt>"));

    layout->addStretch(1);

    page->setMinimumSize(sizeHintForWidget(page));

    defaults();

    setMinimumSize(sizeHint());

    _mailEdit->installEventFilter(this);
    _listEdit->installEventFilter(this);
}

void IdentityPreferences::setSettings(const IdentitySettings& settings)
{
   _nameEdit->setText(settings.authorName);
   _localNameEdit->setText(settings.authorLocalizedName);
   _mailEdit->setText(settings.authorEmail);
   _langEdit->setText(settings.languageName);
   _langCodeEdit->setText(settings.languageCode);
   _listEdit->setText(settings.mailingList);

   _timezoneEdit->setText(settings.timeZone);
   
   _pluralFormsBox->setValue(settings.numberOfPluralForms);
   _checkPluralArgumentBox->setChecked(settings.checkPluralArgument);
   _gnuPluralFormHeaderEdit->setText(settings.gnuPluralFormHeader);

   checkTestPluralButton();
}

void IdentityPreferences::mergeSettings(IdentitySettings& settings) const
{
    settings.authorName=_nameEdit->text();
    settings.authorLocalizedName=_localNameEdit->text();
    settings.authorEmail=_mailEdit->text();
    settings.languageName=_langEdit->text();
    settings.languageCode=_langCodeEdit->text();
    settings.mailingList=_listEdit->text();

    settings.timeZone=_timezoneEdit->text();
    
    settings.numberOfPluralForms=_pluralFormsBox->value();
    settings.checkPluralArgument=_checkPluralArgumentBox->isChecked();
    settings.gnuPluralFormHeader=_gnuPluralFormHeaderEdit->text();
}


void IdentityPreferences::defaults()
{
    KBabel::Defaults::Identity defaultIdentity;
   _nameEdit->setText(defaultIdentity.authorName());
   _localNameEdit->setText(defaultIdentity.authorLocalizedName());
   _mailEdit->setText(defaultIdentity.authorEmail());
   _langEdit->setText(defaultIdentity.languageName());
   _langCodeEdit->setText(defaultIdentity.languageCode());
   _listEdit->setText(defaultIdentity.mailingList());
   _timezoneEdit->setText(defaultIdentity.timezone());
   _pluralFormsBox->setValue(defaultIdentity.numberOfPluralForms);
   _checkPluralArgumentBox->setChecked(defaultIdentity.checkPluralArgument);
   _gnuPluralFormHeaderEdit->setText(defaultIdentity.gnuPluralFormHeader);
   
   checkTestPluralButton();
}

bool IdentityPreferences::eventFilter(QObject *o, QEvent *e)
{
    if(e->type() == QEvent::Drop)
    {
        QDropEvent *de = static_cast<QDropEvent*>(e);
        KURL::List urlList;
        if(de && KURLDrag::decode(de,urlList))
        {
            KURL url(urlList.first());
            if(url.protocol()== "mailto")
            {
                QString mail=url.path();

                bool handled=false;
                if(o == _mailEdit)
                {
                    handled=true;
                    _mailEdit->setText(mail);
                }
                else if(o == _listEdit)
                {
                    handled=true;
                    _listEdit->setText(mail);
                }

                if(handled)
                    return true;
            }
        }
    }

    return false;
}

void IdentityPreferences::checkTestPluralButton()
{
    int val = _pluralFormsBox->value();
    QString lang=_langCodeEdit->text();
    
    _testPluralButton->setEnabled(val==0 && !lang.isEmpty());
}

void IdentityPreferences::testPluralForm()
{
    QString lang=_langCodeEdit->text();

    if(lang.isEmpty())
    {
        KMessageBox::sorry(this,i18n("Please insert a language code first."));
        return;
    }

    int number=Catalog::getNumberOfPluralForms(lang);

    QString msg;
    
    if(number < 0)
    {
        msg = i18n("It is not possible to find out the number "
                "of singular/plural forms automatically for the "
                "language code \"%1\".\n"
                "Do you have kdelibs.po installed for this language?\n"
                "Please set the correct number manually.").arg(lang);
    }
    else
    {
        msg = i18n("The number of singular/plural forms found for "
                "the language code \"%1\" is %2.").arg(lang).arg(number);
    }

    if(!msg.isEmpty())
    {
        KMessageBox::information(this,msg);
    }
}

void IdentityPreferences::lookupGnuPluralFormHeader()
{
    QString lang=_langCodeEdit->text();

    if(lang.isEmpty())
    {
        KMessageBox::sorry(this,i18n("Please insert a language code first."));
        return;
    }

    QString header=GNUPluralForms(lang);
    
    if( header.isEmpty() )
    {
	KMessageBox::information(this, i18n("It was not possible to determine "
	"GNU header for plural forms. Maybe your GNU gettext tools are too "
	"old or they do not contain a suggested value for your language.") );
    }
    else
    {
	_gnuPluralFormHeaderEdit->setText( header );
    }
}



EditorPreferences::EditorPreferences(QWidget* parent)
         : KTabCtl(parent)
{
    QWidget* page= new QWidget(this);
    QVBoxLayout* layout=new QVBoxLayout(page);
    layout->setSpacing(KDialog::spacingHint());
    layout->setMargin(KDialog::marginHint());

    QGroupBox* box=new QGroupBox(2,Qt::Horizontal,page);
    layout->addWidget(box);
    box->setMargin(KDialog::marginHint());
    _fuzzyButton = new QCheckBox(i18n("A&utomatically unset fuzzy status"),box);


    QWhatsThis::add(_fuzzyButton,i18n("<qt><p><b>Automatically unset fuzzy status</b></p>\n"
"<p>If this is activated and you are editing a fuzzy entry, the fuzzy status is automatically\n"
"unset (this means the string <i>, fuzzy</i>\n"
"is removed from the entry's comment).</p></qt>"));

    _cleverEditButton = new QCheckBox(i18n("Use cle&ver editing"),box);
    QWhatsThis::add(_cleverEditButton
        ,i18n("<qt><p><b>Use clever editing</b></p>\n"
              "<p>Check this to make typing text more comfortable and let "
              "KBabel take care of some special characters that have to "
              "be quoted. For example typing '\"' will result in "
              "'\\\"', pressing Return will automatically add whitespace "
              "at the end of the line, pressing Shift+Return will add "
              "'\\n' at the end of the line.</p>\n"
              "<p>Note that this is just a hint and it's still possible to "
              "generate syntactically incorrect text.</p></qt>"));

    box = new QGroupBox(6,Qt::Vertical,i18n("Automatic Checks"), page);
        layout->addWidget(box);
    box->setMargin(KDialog::marginHint());
    
    QValueList<KDataToolInfo> tools = ToolAction::validationTools();
    _checks = new ToolSelectionWidget( "validate", tools,  box );

    _beepButton = new QCheckBox(i18n("&Beep on error"),box);
    _colorErrorButton = new QCheckBox(i18n("Change te&xt color on error"),box);

    QString msg = i18n("<qt><p><b>Error recognition</b></p>"
        "<p>Here you can set how to show that an error occurred. "
        "<b>Beep on error</b> beeps and <b>Change text color on error"
        "</b> changes the color of the translated text. If none is "
        "activated, you will still see a message in the statusbar."
        "</p></qt>");

    QWhatsThis::add(_beepButton,msg);
    QWhatsThis::add(_colorErrorButton,msg);

    layout->addStretch(1);

    page->setMinimumSize(sizeHintForWidget(page));

    addTab(page,i18n("&General"));

    page= new QWidget(this);
    layout=new QVBoxLayout(page);
    layout->setSpacing(KDialog::spacingHint());
    layout->setMargin(KDialog::marginHint());

    box=new QGroupBox(2,Qt::Horizontal,page);
    layout->addWidget(box);
    box->setMargin(KDialog::marginHint());

    _hlSyntaxButton = new QCheckBox(i18n("H&ighlight syntax"),box);
    _spacePointsButton = new QCheckBox(i18n("Mark &whitespaces with points"),box);
    _hlBgButton = new QCheckBox(i18n("Highlight backgrou&nd"),box);
    _quotesButton = new QCheckBox(i18n("&Show surrounding quotes"),box);

    QWhatsThis::add(box,i18n("<qt><p><b>Appearance</b></p>"
"<p>These options let you configure the appearance for the message editor.</p>"
"<p>Check <b>Highlight syntax</b> to let KBabel display special characters, "
"like \\\" and \\n, in different colors.</p>"
"<p>The three other options will help you to \"see\" whitespace characters. "
"<b>Mark whitespace with points</b> draws a small point instead of a whitespace, "
"<b>Highlight background</b> colors the background of the characters and "
"<b>Show surrounding quotes</b> displays quotes at the beginning and end "
"of each line.</p></qt>"));


    box= new QGroupBox(2,Qt::Horizontal,i18n("Colors"),page);
    layout->addWidget(box);
    box->setMargin(KDialog::marginHint());

    QLabel* tempLabel = new QLabel(i18n("&Background color:"),box);
    _bgColorButton = new KColorButton(box);
    tempLabel->setBuddy(_bgColorButton);

    tempLabel = new QLabel(i18n("Color for &quoted characters:"),box);
    _quotedColorButton = new  KColorButton(box);
    tempLabel->setBuddy(_quotedColorButton);

    tempLabel = new QLabel(i18n("Color for s&yntax errors:"),box);
    _errorColorButton = new  KColorButton(box);
    tempLabel->setBuddy(_errorColorButton);

    tempLabel = new QLabel(i18n("Color for c-for&mat characters:"),box);
    _cformatColorButton = new  KColorButton(box);
    tempLabel->setBuddy(_cformatColorButton);

    tempLabel = new QLabel(i18n("Color for &keyboard accelerators:"),box);
    _accelColorButton = new  KColorButton(box);
    tempLabel->setBuddy(_accelColorButton);

    tempLabel = new QLabel(i18n("Color for &tags:"),box);
    _tagColorButton = new  KColorButton(box);
    tempLabel->setBuddy(_tagColorButton);

    QWhatsThis::add(box,i18n("<qt><p><b>Colors</b></p>"
"<p>Define here which colors you want to be used in the Editor. "
"<b>Background color</b> is used for highlighting the background of characters. "
"The other colors are used for syntax highlighting.</p></qt>"));



    box=new QGroupBox(2,Qt::Horizontal,i18n("Status LEDs"),page);
    layout->addWidget(box);
    box->setMargin(KDialog::marginHint());

    QButtonGroup* bgBox=new QButtonGroup(2,Qt::Horizontal,box);
    bgBox->setFrameStyle(QFrame::NoFrame);
    _ledInStatusbarBtn = new QRadioButton(i18n("Display in stat&usbar"),bgBox);
    _ledInEditorBtn = new QRadioButton(i18n("Display in edi&tor"),bgBox);

    QHBox* hBox=new QHBox(box);
    hBox->setSpacing(KDialog::spacingHint());
    tempLabel = new QLabel(i18n("Colo&r:"),hBox);
    _ledColorButton = new  KColorButton(hBox);
    tempLabel->setBuddy(_ledColorButton);
    tempLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);

    QWhatsThis::add(box,i18n("<qt><p><b>Status LEDs</b></p>\n"
"<p>Choose here where the status LEDs are displayed and what color they have.</p></qt>"));


    layout->addStretch(1);
    page->setMinimumSize(sizeHintForWidget(page));

    addTab(page,i18n("A&ppearance"));


    page= new QWidget(this);
    layout=new QVBoxLayout(page);
    layout->setSpacing(KDialog::spacingHint());
    layout->setMargin(KDialog::marginHint());

    box=new QGroupBox(1,Qt::Horizontal,i18n("Font for Messages"),page);
    layout->addWidget(box);
    box->setMargin(KDialog::marginHint());

    _onlyFixedFontsButton = new QCheckBox(i18n("&Show only fixed fonts"),box);
    connect(_onlyFixedFontsButton, SIGNAL(toggled(bool))
            , this, SLOT(showOnlyFixedFonts(bool)) );

    _fontBox = new KFontChooser(box,0,false,QStringList(),false);

    layout->addStretch(1);
    page->setMinimumSize(sizeHintForWidget(page));

    addTab(page,i18n("&Fonts"));


    defaults();

    setMinimumSize(sizeHint());


    connect(_ledInStatusbarBtn,SIGNAL(toggled(bool)),this,SLOT(ledWarning(bool)));
    connect(_ledInEditorBtn,SIGNAL(toggled(bool)),this,SLOT(ledWarning(bool)));
}



void EditorPreferences::setSettings(const EditorSettings& settings)
{
    _fuzzyButton->setChecked(settings.autoUnsetFuzzy);
    _cleverEditButton->setChecked(settings.cleverEditing);
    _beepButton->setChecked(settings.beepOnError);
    _colorErrorButton->setChecked(settings.autoCheckColorError);
    
    _checks->setSelectedTools( settings.autoCheckTools );

    _fontBox->setFont(settings.msgFont);

    _hlSyntaxButton->setChecked(settings.highlightSyntax);
    _hlBgButton->setChecked(settings.highlightBg);
    _quotesButton->setChecked(settings.quotes);
    _spacePointsButton->setChecked(settings.whitespacePoints);

    _bgColorButton->setColor(settings.bgColor);
    _quotedColorButton->setColor(settings.quotedColor);
    _errorColorButton->setColor(settings.errorColor);
    _cformatColorButton->setColor(settings.cformatColor);
    _accelColorButton->setColor(settings.accelColor);
    _tagColorButton->setColor(settings.tagColor);


    _ledInStatusbarBtn->blockSignals(true);
    _ledInEditorBtn->blockSignals(true);
    _ledInStatusbarBtn->setChecked(settings.ledInStatusbar);
    _ledInEditorBtn->setChecked(!settings.ledInStatusbar);
    _ledInStatusbarBtn->blockSignals(false);
    _ledInEditorBtn->blockSignals(false);

    _ledColorButton->setColor(settings.ledColor);
}


void EditorPreferences::mergeSettings(EditorSettings& settings) const
{
    settings.autoUnsetFuzzy=_fuzzyButton->isChecked();
    settings.cleverEditing=_cleverEditButton->isChecked();
    settings.beepOnError=_beepButton->isChecked();
    settings.autoCheckColorError=_colorErrorButton->isChecked();
    
    settings.autoCheckTools = _checks->selectedTools();

    settings.msgFont=_fontBox->font();

    settings.highlightSyntax=_hlSyntaxButton->isChecked();
    settings.highlightBg=_hlBgButton->isChecked();
    settings.quotes=_quotesButton->isChecked();
    settings.whitespacePoints=_spacePointsButton->isChecked();

    settings.quotedColor=_quotedColorButton->color();
    settings.errorColor=_errorColorButton->color();
    settings.cformatColor=_cformatColorButton->color();
    settings.accelColor=_accelColorButton->color();
    settings.tagColor=_tagColorButton->color();

    settings.bgColor=_bgColorButton->color();


    settings.ledInStatusbar=_ledInStatusbarBtn->isChecked();
    settings.ledColor=_ledColorButton->color();
}

void EditorPreferences::defaults()
{
    _fuzzyButton->setChecked(::Defaults::Editor::autoUnsetFuzzy);
    _cleverEditButton->setChecked(::Defaults::Editor::cleverEditing);
    _beepButton->setChecked(::Defaults::Editor::beepOnError);
    _colorErrorButton->setChecked(::Defaults::Editor::autoCheckColorError);
    
    _checks->setSelectedTools( ::Defaults::Editor::autoCheckTools() );
    
    _fontBox->setFont(::Defaults::Editor::msgFont());

    _hlSyntaxButton->setChecked(::Defaults::Editor::highlightSyntax);
    _hlBgButton->setChecked(::Defaults::Editor::highlightBg);
    _quotesButton->setChecked(::Defaults::Editor::quotes);
    _spacePointsButton->setChecked(::Defaults::Editor::whitespacePoints);

    _bgColorButton->setColor(::Defaults::Editor::bgColor);
    _quotedColorButton->setColor(::Defaults::Editor::quotedColor);
    _errorColorButton->setColor(::Defaults::Editor::errorColor);
    _cformatColorButton->setColor(::Defaults::Editor::cformatColor);
    _accelColorButton->setColor(::Defaults::Editor::accelColor);
    _tagColorButton->setColor(::Defaults::Editor::tagColor);


    _ledInStatusbarBtn->setChecked(::Defaults::Editor::ledInStatusbar);
    _ledInEditorBtn->setChecked(!::Defaults::Editor::ledInStatusbar);
    _ledColorButton->setColor(::Defaults::Editor::ledColor);
}


void EditorPreferences::showOnlyFixedFonts(bool on)
{
   _fontBox->setFont(_fontBox->font(),on);
}


void EditorPreferences::ledWarning(bool show)
{
   if(show)
      KMessageBox::information( this,i18n("This option takes no effect until KBabel is restarted.") );
}



SearchPreferences::SearchPreferences(QPtrList<ModuleInfo> ml,QWidget* parent)
         : QWidget(parent)
{
    moduleList = ml;
    moduleList.setAutoDelete(true);

    // first page
    QWidget* page= this;
    QVBoxLayout* layout=new QVBoxLayout(page);
    layout->setSpacing(KDialog::spacingHint());
    layout->setMargin(KDialog::marginHint());

    QGroupBox* box=new QGroupBox(1,Qt::Horizontal,page);
    layout->addWidget(box);
    box->setMargin(KDialog::marginHint());
    _searchButton = new QCheckBox(i18n("Au&tomatically start search"),box);

    QWhatsThis::add(_searchButton,i18n(
        "<qt><p><b>Automatically start search</b></p>"
        "<p>If this is activated, the search is automatically started "
        "whenever you switch to another entry in the editor. You can "
        "choose where to search with the combo box <b>Default Dictionary</b>."
        "</p><p>You can also start searching manually by choosing an entry in "
        "the popup menu that appears either when clicking "
        "<b>Dictionaries->Find...</b> or keeping the dictionary button "
        "in the toolbar pressed for a while.</p></qt>"));

    QHBox *hb = new QHBox(box);
    QLabel *label = new QLabel(i18n("D&efault dictionary:"),hb);
    _defaultModuleBox = new KComboBox(hb,"defaultModuleBox");
    _defaultModuleBox->setAutoCompletion(true);
    label->setBuddy(_defaultModuleBox);

    ModuleInfo *info;
    for(info = ml.first(); info != 0; info = ml.next())
    {
        _defaultModuleBox->insertItem(info->name);
    }

    QString msg=i18n("<qt><p><b>Default Dictionary</b></p>\n"
        "<p>Choose here where to search as default. "
        "This setting is used when searching is started automatically "
        "or when pressing the dictionary button in the toolbar.</p>"
        "<p>You can configure the different dictionaries by selecting "
        "the desired dictionary from <b>Settings->Configure Dictionary</b>."
        "</p></qt>");

    QWhatsThis::add(_defaultModuleBox,msg);
    QWhatsThis::add(label,msg);


    layout->addStretch(1);

    page->setMinimumSize(sizeHintForWidget(page));


    defaults();


    setMinimumSize(sizeHint());
}


SearchPreferences::~SearchPreferences()
{
}


void SearchPreferences::setSettings(const SearchSettings& settings)
{
    _searchButton->setChecked(settings.autoSearch);

    int i=0;
    ModuleInfo *info;
    for(info = moduleList.first(); info != 0; info = moduleList.next())
    {
        if(settings.defaultModule == info->id)
            break;

        i++;
    }
    
    _defaultModuleBox->setCurrentItem(i);
}


void SearchPreferences::mergeSettings(SearchSettings& settings)
{
    settings.autoSearch=_searchButton->isChecked();
    
    int i=_defaultModuleBox->currentItem();
    ModuleInfo *info = moduleList.at(i);

    if(info)
        settings.defaultModule=info->id;
}



void SearchPreferences::defaults()
{
    _searchButton->setChecked(::Defaults::Search::autoSearch);
    
    int i=0;
    ModuleInfo *info;
    for(info = moduleList.first(); info != 0; info = moduleList.next())
    {
        if(::Defaults::Search::defaultModule == info->id)
            break;

        i++;
    }

    _defaultModuleBox->setCurrentItem(i);
}

MiscPreferences::MiscPreferences(QWidget *parent)
                : QWidget(parent), _regExpEditDialog(0)
{
    QWidget* page = this;

    QVBoxLayout* layout=new QVBoxLayout(page);
    layout->setSpacing(KDialog::spacingHint());
    layout->setMargin(KDialog::marginHint());

    QGroupBox* box=new QGroupBox(1,Qt::Horizontal,page);
    box->setMargin(KDialog::marginHint());
    layout->addWidget(box);

    QHBox *hbox = new QHBox(box);
    hbox->setSpacing(KDialog::spacingHint());

    QLabel *label = new QLabel(i18n("&Marker for keyboard accelerator:"),hbox);
    accelMarkerEdit = new KLineEdit(hbox);
    accelMarkerEdit->setMaxLength(1);
    label->setBuddy(accelMarkerEdit);
    hbox->setStretchFactor(accelMarkerEdit,1);
    QString msg=i18n("<qt><p><b>Marker for keyboard accelerator</b></p>"
        "<p>Define here, what character marks the following "
        "character as keyboard accelerator. For example in Qt it is "
        "'&amp;' and in Gtk it is '_'.</p></qt>");
    QWhatsThis::add(label,msg);
    QWhatsThis::add(accelMarkerEdit,msg);



    hbox = new QHBox(box);
    hbox->setSpacing(KDialog::spacingHint());

    label = new QLabel(i18n("&Regular expression for context information:")
            ,hbox);
    contextInfoEdit = new KLineEdit(hbox);
    label->setBuddy(contextInfoEdit);
    hbox->setStretchFactor(contextInfoEdit,1);

    msg=i18n("<qt><p><b>Regular expression for context information</b></p>"
        "<p>Enter a regular expression here which defines what is "
        "context information in the message and must not get "
        "translated.</p></qt>");
    QWhatsThis::add(label,msg);
    QWhatsThis::add(contextInfoEdit,msg);

    if( !KTrader::self()->query("KRegExpEditor/KRegExpEditor").isEmpty() )
    {
	_regExpButton = new QPushButton( i18n("&Edit..."), hbox );
	connect( _regExpButton, SIGNAL( clicked() ), this, SLOT( regExpButtonClicked()));
    }


    // preferences for mail attachments
    QVButtonGroup* vbgroup = new QVButtonGroup(page);
    vbgroup->setTitle(i18n("Compression Method for Mail Attachments"));
    vbgroup->setRadioButtonExclusive(true);
    vbgroup->setMargin(KDialog::marginHint());
    layout->addWidget(vbgroup);

    bzipButton = new QRadioButton(i18n("tar/&bzip2"), vbgroup);
    gzipButton = new QRadioButton(i18n("tar/&gzip"), vbgroup);

    compressSingle = new QCheckBox(i18n("&Use compression when sending "
					"a single file"), vbgroup);

    layout->addStretch(1);
    page->setMinimumSize(sizeHintForWidget(page));
}

MiscPreferences::~MiscPreferences()
{
}

void MiscPreferences::defaults()
{
   KBabel::Defaults::Misc defaultMisc;
   accelMarkerEdit->setText(defaultMisc.accelMarker());
   setContextInfo(defaultMisc.contextInfo().pattern());

   if (defaultMisc.useBzip) {
     bzipButton->setChecked(true);
   } else {
     gzipButton->setChecked(true);
   }
   compressSingle->setChecked(defaultMisc.compressSingleFile);
}

void MiscPreferences::setSettings(const MiscSettings& settings)
{
   accelMarkerEdit->setText(settings.accelMarker);
   setContextInfo(settings.contextInfo.pattern());

   if (settings.useBzip) {
     bzipButton->setChecked(true);
   } else {
     gzipButton->setChecked(true);
   }
   compressSingle->setChecked(settings.compressSingleFile);
}

void MiscPreferences::mergeSettings(MiscSettings& settings) const
{
    KBabel::Defaults::Misc d;
    QString temp=accelMarkerEdit->text();
    if(temp.isEmpty())
    {
        temp=d.accelMarker();
        accelMarkerEdit->setText(temp);
    }
    settings.accelMarker=temp[0];

    settings.contextInfo.setPattern(contextInfo());

    settings.useBzip = bzipButton->isChecked();
    settings.compressSingleFile = compressSingle->isChecked();
}


QString MiscPreferences::contextInfo() const
{
    QString temp=contextInfoEdit->text();

    bool quoted=false;
    QString newStr;

    for(uint i=0; i<temp.length(); i++)
    {
        if(temp[i]=='n')
        {
            quoted=!quoted;
            newStr+=temp[i];
        }
        else if(temp[i]=='n' && quoted)
        {
            newStr[newStr.length()-1]='\n';
            quoted=false;
        }
        else
        {
            quoted=false;
            newStr+=temp[i];
        }
    }

    return newStr;
}

void MiscPreferences::setContextInfo(QString reg)
{
    reg.replace("\n","\\n");
    contextInfoEdit->setText(reg);
}

void MiscPreferences::regExpButtonClicked()
{
    if ( _regExpEditDialog==0 )
      _regExpEditDialog = KParts::ComponentFactory::createInstanceFromQuery<QDialog>
	("KRegExpEditor/KRegExpEditor", QString::null, this );

    KRegExpEditorInterface *iface = dynamic_cast<KRegExpEditorInterface *>( _regExpEditDialog );
    if( iface )
    {
	iface->setRegExp( contextInfoEdit->text() );
	if( _regExpEditDialog->exec() == QDialog::Accepted )
	    contextInfoEdit->setText( iface->regExp() );
    }
}

DiffPreferences::DiffPreferences(QWidget* parent)
         : QWidget(parent)
{
    QWidget* page= this;
    QVBoxLayout* layout=new QVBoxLayout(page);
    layout->setSpacing(KDialog::spacingHint());
    layout->setMargin(KDialog::marginHint());
    

    QGroupBox *box= new QGroupBox(2,Qt::Horizontal,i18n("Appearance"),page);
    layout->addWidget(box);
    box->setMargin(KDialog::marginHint());
    
    QLabel *tempLabel = new QLabel(i18n("Added characters:"),box);
    box->addSpace(0);
    tempLabel = new QLabel(i18n("Ho&w to display:"),box);
    _diffAddCombo = new KComboBox(box);
    _diffAddCombo->insertItem(i18n("Highlighted"));
    _diffAddCombo->insertItem(i18n("Underlined"));
    tempLabel->setBuddy(_diffAddCombo);

    tempLabel = new QLabel(i18n("Co&lor:"),box);
    _diffAddColorBtn = new KColorButton(box);
    tempLabel->setBuddy(_diffAddColorBtn);

    tempLabel = new QLabel(i18n("Removed characters:"),box);
    box->addSpace(0);

    tempLabel = new QLabel(i18n("How &to display:"),box);
    _diffDelCombo = new KComboBox(box);
    _diffDelCombo->insertItem(i18n("Highlighted"));
    _diffDelCombo->insertItem(i18n("Stroked Out"));
    tempLabel->setBuddy(_diffDelCombo);

    tempLabel = new QLabel(i18n("Colo&r:"),box);
    _diffDelColorBtn = new KColorButton(box);
    tempLabel->setBuddy(_diffDelColorBtn);

    QVButtonGroup* bbox= new QVButtonGroup(i18n("Diff Source"),page);
    bbox->setMargin(KDialog::marginHint());
    layout->addWidget(bbox);

    _fileSourceBtn = new QRadioButton( i18n("Use &file"), bbox );
    _dbSourceBtn = new QRadioButton(
            i18n("Use messages from &translation database"),bbox);
    _msgstrSourceBtn = new QRadioButton( i18n("Use &msgstr from the same file"), bbox);    

    QWhatsThis::add(bbox,
         i18n("<qt><p><b>Source for difference lookup</b></p>"
             "<p>Here you can select a source, which should be used "
	     "for finding a difference.</p>"
	     "<p>You can select file, translation database or "
	     "corresponding msgstr.</p>"
	     "<p>If you choose the translatio database, the messages to diff with are "
             "taken from the Translation Database. To be useful you have "
             "to enable <i>Auto add entry to database</i> in its "
             "preferences dialog.</p>"
	     "<p>The last option is useful for those using PO-files "
	     "for proofreading.</p>"
             "<p>You can temporarily diff with messages from a file "
             "by choosing <i>Tools->Diff->Open file for diff</i> "
             "in KBabel's main window.</p></qt>"));
    
    QHBox *hbox = new QHBox(page);
    layout->addWidget(hbox);
    hbox->setSpacing(KDialog::spacingHint());
    tempLabel = new QLabel(i18n("Base folder for diff files:"),hbox);
   _diffBaseDirEdit = new KURLRequester(hbox);
   _diffBaseDirEdit->setMode( static_cast<KFile::Mode>(KFile::Directory
               | KFile::ExistingOnly | KFile::LocalOnly) );

   QString msg = i18n("<qt><q><b>Base folder for diff files</b></q>\n"
           "<p>Here you can define a folder in which the files to "
           "diff with are stored. If the files are stored at the same "
           "place beneath this folder as the original files beneath "
           "their base folder, KBabel can automatically open the correct "
           "file to diff with.</p>"
           "<p>Note that this option has no effect if messages from "
           "the database are used for diffing.</p></qt>");
   QWhatsThis::add(tempLabel,msg);
   QWhatsThis::add(_diffBaseDirEdit,msg);
   QWhatsThis::add(hbox,msg);

   layout->addStretch(1);

    defaults();

    setMinimumSize(sizeHint());
}



void DiffPreferences::setSettings(const EditorSettings& settings)
{
    _diffAddColorBtn->setColor(settings.diffAddColor);
    _diffDelColorBtn->setColor(settings.diffDelColor);

    if(settings.diffAddUnderline)
    {
        _diffAddCombo->setCurrentItem(1);
    }
    else
    {
        _diffAddCombo->setCurrentItem(0);
    }
 
    if(settings.diffDelStrikeOut)
    {
        _diffDelCombo->setCurrentItem(1);
    }
    else
    {
        _diffDelCombo->setCurrentItem(0);
    }
       
    _diffBaseDirEdit->setURL(settings.diffBaseDir);
    
    switch( settings.diffSource )
    {
	case EditorSettings::File: 
	    _fileSourceBtn->setChecked(true);
	    break;
	case EditorSettings::Database: 
	    _dbSourceBtn->setChecked(true);
	    break;
	case EditorSettings::Msgstr: 
	    _msgstrSourceBtn->setChecked(true);
	    break;
    }
}


void DiffPreferences::mergeSettings(EditorSettings& settings) const
{
    settings.diffAddColor = _diffAddColorBtn->color();
    settings.diffDelColor = _diffDelColorBtn->color();
    if(_diffAddCombo->currentItem() == 0)
        settings.diffAddUnderline=false;
    else
        settings.diffAddUnderline=true;
    
    if(_diffDelCombo->currentItem() == 0)
        settings.diffDelStrikeOut=false;
    else
        settings.diffDelStrikeOut=true;

    settings.diffSource = ::Defaults::Editor::diffSource;

    settings.diffBaseDir = _diffBaseDirEdit->url();
    if( _fileSourceBtn->isChecked() )
    {
	settings.diffSource = EditorSettings::File;
    }
    else if( _dbSourceBtn->isChecked() )
    {
	settings.diffSource = EditorSettings::Database;
    }
    else
    {
	settings.diffSource = EditorSettings::Msgstr;
    }    
}

void DiffPreferences::defaults()
{
    _diffAddColorBtn->setColor(::Defaults::Editor::diffAddColor);
    _diffDelColorBtn->setColor(::Defaults::Editor::diffDelColor);

    if(::Defaults::Editor::diffAddUnderline)
    {
        _diffAddCombo->setCurrentItem(1);
    }
    else
    {
        _diffAddCombo->setCurrentItem(0);
    }
 
    if(::Defaults::Editor::diffDelStrikeOut)
    {
        _diffDelCombo->setCurrentItem(1);
    }
    else
    {
        _diffDelCombo->setCurrentItem(0);
    }
    
    _diffBaseDirEdit->setURL(::Defaults::Editor::diffBaseDir);

    switch( ::Defaults::Editor::diffSource )
    {
	case EditorSettings::File: 
	    _fileSourceBtn->setChecked(true);
	    break;
	case EditorSettings::Database: 
	    _dbSourceBtn->setChecked(true);
	    break;
	case EditorSettings::Msgstr: 
	    _msgstrSourceBtn->setChecked(true);
	    break;
    }
}


SpellPreferences::SpellPreferences(QWidget* parent)
         : QWidget(parent)
{
    QWidget* page = this;
    QVBoxLayout* layout=new QVBoxLayout(page);
    layout->setSpacing(KDialog::spacingHint());
    layout->setMargin(KDialog::marginHint());


    onFlyBtn = new QCheckBox(i18n("On the &fly spellchecking"),page);
    layout->addWidget(onFlyBtn);

    QWhatsThis::add(onFlyBtn, i18n("<qt><p><b>On the fly spellchecking</b></p>"
        "<p>Activate this to let KBabel spell check the text "
	"as you type. Mispelled words will be colored by the error color.</p></qt>"));
	
    spellConfig = new KSpellConfig(page,"spellConfigWidget",0,false);
    layout->addWidget(spellConfig);
    remIgnoredBtn = new QCheckBox(i18n("&Remember ignored words"),page);
    layout->addWidget(remIgnoredBtn);

    QLabel *tempLabel = new QLabel(i18n("F&ile to store ignored words:"),page);
    layout->addWidget(tempLabel);
    ignoreURLEdit = new KURLRequester(page);
    layout->addWidget(ignoreURLEdit);
    tempLabel->setBuddy(ignoreURLEdit);

    connect(remIgnoredBtn,SIGNAL(toggled(bool)),ignoreURLEdit
                        ,SLOT(setEnabled(bool)));


    QString msg = i18n("<qt><p><b>Remember ignored words</b></p>"
        "<p>Activate this, to let KBabel ignore the words, where you have "
        "chosen <i>Ignore All</i> in the spell check dialog, "
        "in every spell check.</p></qt>");

    QWhatsThis::add(remIgnoredBtn,msg);
    QWhatsThis::add(tempLabel,msg);
    QWhatsThis::add(ignoreURLEdit,msg);

    layout->addStretch(1);

    page->setMinimumSize(sizeHintForWidget(page));

    defaults();

    setMinimumSize(sizeHint());
}



void SpellPreferences::setSettings(const SpellcheckSettings& settings)
{
    spellConfig->setNoRootAffix(settings.noRootAffix);
    spellConfig->setRunTogether(settings.runTogether);
    spellConfig->setClient(settings.spellClient);
    spellConfig->setEncoding(settings.spellEncoding);
    spellConfig->setDictionary(settings.spellDict);

    remIgnoredBtn->setChecked(settings.rememberIgnored);
    ignoreURLEdit->setURL(settings.ignoreURL);
    
    onFlyBtn->setChecked(settings.onFlySpellcheck);
}


void SpellPreferences::mergeSettings(SpellcheckSettings& settings) const
{
    settings.noRootAffix=spellConfig->noRootAffix();
    settings.runTogether=spellConfig->runTogether();
    settings.spellClient=spellConfig->client();
    settings.spellEncoding=spellConfig->encoding();
    settings.spellDict=spellConfig->dictionary();

    settings.rememberIgnored=remIgnoredBtn->isChecked();
    settings.ignoreURL=ignoreURLEdit->url();
    
    settings.onFlySpellcheck=onFlyBtn->isChecked();
    
    settings.valid=true;
}

void SpellPreferences::defaults()
{
    remIgnoredBtn->setChecked(::Defaults::Spellcheck::rememberIgnored);
    ignoreURLEdit->setURL(::Defaults::Spellcheck::ignoreURL());
    
    onFlyBtn->setChecked(::Defaults::Spellcheck::onFlySpellcheck);

    KSpellConfig spCfg;
    *spellConfig = spCfg;
}

#include "prefwidgets.moc"
