/**
 * Copyright (C) 2003 Joonas Koivunen <rzei@mbnet.fi>
 * Copyright (C) 2003 Koos Vriezen <koos.vriezen@xs4all.nl>
 *
 * 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 of the License, or (at your option) any later version.
 *
 * 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 Steet, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#undef Always

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <tqlayout.h>
#include <tqlabel.h>
#include <tqpushbutton.h>
#include <tqradiobutton.h>
#include <tqcheckbox.h>
#include <tqstringlist.h>
#include <tqcombobox.h>
#include <tqlineedit.h>
#include <tqgroupbox.h>
#include <tqwhatsthis.h>
#include <tqtabwidget.h>
#include <tqslider.h>
#include <tqbuttongroup.h>
#include <tqspinbox.h>
#include <tqmessagebox.h>
#include <tqmap.h>
#include <tqtimer.h>
#include <tqfont.h>

#include <tdelocale.h>
#include <kdebug.h>
#include <tdefiledialog.h>
#include <tdemessagebox.h>
#include <klineedit.h>
#include <kiconloader.h>
#include <tdeversion.h>
#include <kcombobox.h>
#include <kcolorbutton.h>
#include <kurlrequester.h>
#include <tdefontdialog.h>

#include "pref.h"
#include "kmplayerpartbase.h"
#include "kmplayerprocess.h"
#include "kmplayerconfig.h"


using namespace KMPlayer;

KDE_NO_CDTOR_EXPORT Preferences::Preferences(PartBase * player, Settings * settings)
: KDialogBase (IconList, i18n ("Preferences"),
		Help|Default|Ok|Apply|Cancel, Ok, player->view (), 0, false)
{
    TQFrame *frame;
    TQTabWidget * tab;
    TQStringList hierarchy; // typo? :)
    TQVBoxLayout *vlay;

    frame = addPage(i18n("General Options"), TQString(), TDEGlobal::iconLoader()->loadIcon (TQString ("kmplayer"), TDEIcon::NoGroup, 32));
    vlay = new TQVBoxLayout(frame, marginHint(), spacingHint());
    tab = new TQTabWidget (frame);
    vlay->addWidget (tab);
    m_GeneralPageGeneral = new PrefGeneralPageGeneral (tab, settings);
    tab->insertTab (m_GeneralPageGeneral, i18n("General"));
    m_GeneralPageLooks = new PrefGeneralPageLooks (tab, settings);
    tab->insertTab (m_GeneralPageLooks, i18n("Looks"));
    m_GeneralPageOutput = new PrefGeneralPageOutput
        (tab, settings->audiodrivers, settings->videodrivers);
    tab->insertTab (m_GeneralPageOutput, i18n("Output"));
    entries.insert (i18n("General Options"), tab);

    frame = addPage (i18n ("Source"), TQString(), TDEGlobal::iconLoader()->loadIcon (TQString ("text-x-src"), TDEIcon::NoGroup, 32));
    vlay = new TQVBoxLayout (frame, marginHint(), spacingHint());
    tab = new TQTabWidget (frame);
    vlay->addWidget (tab);
    m_SourcePageURL = new PrefSourcePageURL (tab);
    tab->insertTab (m_SourcePageURL, i18n ("URL"));
    entries.insert (i18n("Source"), tab);

    frame = addPage (i18n ("Recording"), TQString(), TDEGlobal::iconLoader()->loadIcon (TQString ("video-x-generic"), TDEIcon::NoGroup, 32));
    vlay = new TQVBoxLayout (frame, marginHint(), spacingHint());
    tab = new TQTabWidget (frame);
    vlay->addWidget (tab);

    int recorders_count = 3;
    m_MEncoderPage = new PrefMEncoderPage (tab, player);
    tab->insertTab (m_MEncoderPage, i18n ("MEncoder"));
    recorders = m_MEncoderPage;

    m_FFMpegPage = new PrefFFMpegPage (tab, player);
    tab->insertTab (m_FFMpegPage, i18n ("FFMpeg"));
    m_MEncoderPage->next = m_FFMpegPage;

    m_MPlayerDumpstreamPage = new PrefMPlayerDumpstreamPage (tab, player);
    // tab->insertTab (m_MPlayerDumpstreamPage, i18n ("MPlayer -dumpstream"));
    m_FFMpegPage->next = m_MPlayerDumpstreamPage;
#ifdef HAVE_XINE
    recorders_count = 4;
    m_XinePage = new PrefXinePage (tab, player);
    // tab->insertTab (m_XinePage, i18n ("Xine"));
    m_MPlayerDumpstreamPage->next = m_XinePage;
#endif
    m_RecordPage = new PrefRecordPage (tab, player, recorders, recorders_count);
    tab->insertTab (m_RecordPage, i18n ("General"), 0);
    tab->setCurrentPage (0);
    entries.insert (i18n("Recording"), tab);

    frame = addPage (i18n ("Output Plugins"), TQString(), TDEGlobal::iconLoader()->loadIcon (TQString ("image-x-generic"), TDEIcon::NoGroup, 32));
    vlay = new TQVBoxLayout(frame, marginHint(), spacingHint());
    tab = new TQTabWidget (frame);
    vlay->addWidget (tab);
    m_OPPagePostproc = new PrefOPPagePostProc (tab);
    tab->insertTab (m_OPPagePostproc, i18n ("Postprocessing"));
    entries.insert (i18n("Postprocessing"), tab);

    for (PreferencesPage * p = settings->pagelist; p; p = p->next)
        addPrefPage (p);
        

    connect (this, TQ_SIGNAL (defaultClicked ()), TQ_SLOT (confirmDefaults ()));
}

KDE_NO_EXPORT void Preferences::setPage (const char * name) {
    TQObject * o = child (name, "TQFrame");
    if (!o) return;
    TQFrame * page = static_cast <TQFrame *>(o);
    TQWidget * w = page->parentWidget ();
    while (w && !w->inherits ("TQTabWidget"))
        w = w->parentWidget ();
    if (!w) return;
    TQTabWidget * t = static_cast <TQTabWidget*> (w);
    t->setCurrentPage (t->indexOf(page));
    if (!t->parentWidget() || !t->parentWidget()->inherits ("TQFrame"))
        return;
    showPage (pageIndex (t->parentWidget ()));
}

KDE_NO_EXPORT void Preferences::addPrefPage (PreferencesPage * page) {
    TQString item, subitem, icon;
    TQFrame * frame;
    TQTabWidget * tab;
    TQVBoxLayout *vlay;
    page->prefLocation (item, icon, subitem);
    if (item.isEmpty ())
        return;
    TQMap<TQString, TQTabWidget *>::iterator en_it = entries.find (item);
    if (en_it == entries.end ()) {
        frame = addPage (item, TQString(), TDEGlobal::iconLoader()->loadIcon ((icon), TDEIcon::NoGroup, 32));
        vlay = new TQVBoxLayout (frame, marginHint(), spacingHint());
        tab = new TQTabWidget (frame);
        vlay->addWidget (tab);
        entries.insert (item, tab);
    } else
        tab = en_it.data ();
    frame = page->prefPage (tab);
    tab->insertTab (frame, subitem);
}

KDE_NO_EXPORT void Preferences::removePrefPage(PreferencesPage * page) {
    TQString item, subitem, icon;
    page->prefLocation (item, icon, subitem);
    if (item.isEmpty ())
        return;
    TQMap<TQString, TQTabWidget *>::iterator en_it = entries.find (item);
    if (en_it == entries.end ())
        return;
    TQTabWidget * tab = en_it.data ();
    for (int i = 0; i < tab->count (); i++)
        if (tab->label (i) == subitem) {
            TQWidget * w = tab->page (i);
            tab->removePage (w);
            delete w;
            break;
        }
    if (!tab->count ()) {
        TQWidget * w = tab->parentWidget ();
        while (w && !w->inherits ("TQFrame"))
            w = w->parentWidget ();
        delete w;
        entries.erase (en_it);
    }
}

KDE_NO_CDTOR_EXPORT Preferences::~Preferences() {
}

KDE_NO_CDTOR_EXPORT PrefGeneralPageGeneral::PrefGeneralPageGeneral(TQWidget *parent, Settings *)
: TQFrame (parent, "GeneralPage")
{
    TQVBoxLayout *layout = new TQVBoxLayout(this, 5, 2);

    TQGroupBox *windowbox = new TQGroupBox(1, TQt::Vertical, i18n("Window"), this);
    TQWidget * wbox = new TQWidget (windowbox);
    TQWidget * bbox = new TQWidget (wbox);
    TQGridLayout * gridlayout = new TQGridLayout (bbox, 2, 2);
    keepSizeRatio = new TQCheckBox (i18n ("Keep size ratio"), bbox, 0);
    TQWhatsThis::add(keepSizeRatio, i18n("When checked, movie will keep its aspect ratio\nwhen window is resized"));
    dockSysTray = new TQCheckBox (i18n ("Dock in system tray"), bbox, 0);
    TQWhatsThis::add (dockSysTray, i18n ("When checked, an icon of KMPlayer will be added to the system tray.\nWhen clicked it will hide KMPlayer's main window and removing KMPlayer's taskbar button."));
    autoResize = new TQCheckBox (i18n ("Auto resize to video sizes"), bbox);
    TQWhatsThis::add (autoResize, i18n("When checked, KMPlayer will resize to movie sizes\nwhen video starts"));
    gridlayout->addWidget (keepSizeRatio, 0, 0);
    gridlayout->addWidget (dockSysTray, 1, 0);
    gridlayout->addWidget (autoResize, 0, 1);
    sizesChoice = new TQButtonGroup (2, TQt::Vertical, wbox);
    new TQRadioButton (i18n("Remember window size on exit"), sizesChoice);
    new TQRadioButton (i18n("Always start with fixed size"), sizesChoice);
    TQVBoxLayout * vbox = new TQVBoxLayout (wbox, 2, 2);
    vbox->addWidget (bbox);
    vbox->addWidget (sizesChoice);

    TQGroupBox *playbox =new TQGroupBox(4, TQt::Vertical,i18n("Playing"),this);
    loop = new TQCheckBox (i18n("Loop"), playbox);
    TQWhatsThis::add(loop, i18n("Makes current movie loop"));
    framedrop = new TQCheckBox (i18n ("Allow framedrops"), playbox);
    TQWhatsThis::add (framedrop, i18n ("Allow dropping frames for better audio and video synchronization"));
    adjustvolume = new TQCheckBox(i18n("Auto set volume on start"), playbox);
    TQWhatsThis::add (adjustvolume, i18n ("When a new source is selected, the volume will be set according the volume control"));
    adjustcolors = new TQCheckBox(i18n("Auto set colors on start"), playbox);
    TQWhatsThis::add (adjustcolors, i18n ("When a movie starts, the colors will be set according the sliders for colors"));

    TQGroupBox * gbox =new TQGroupBox (1, TQt::Vertical, i18n("Control Panel"), this);
    bbox =new TQWidget (gbox);
    //TQGroupBox * bbox = gbox;
    gridlayout = new TQGridLayout (bbox, 3, 2);
    showConfigButton = new TQCheckBox(i18n("Show config button"), bbox);
    TQWhatsThis::add (showConfigButton, i18n ("Add a button that will popup a config menu"));
    showPlaylistButton = new TQCheckBox(i18n("Show playlist button"), bbox);
    TQWhatsThis::add (showPlaylistButton, i18n ("Add a playlist button to the control buttons"));
    showRecordButton = new TQCheckBox(i18n("Show record button"), bbox);
    TQWhatsThis::add (showRecordButton, i18n ("Add a record button to the control buttons"));
    showBroadcastButton = new TQCheckBox (i18n ("Show broadcast button"), bbox);
    TQWhatsThis::add (showBroadcastButton, i18n ("Add a broadcast button to the control buttons"));
    gridlayout->addWidget (showConfigButton, 0, 0);
    gridlayout->addWidget (showPlaylistButton, 0, 1);
    gridlayout->addWidget (showRecordButton, 1, 0);
    gridlayout->addWidget (showBroadcastButton, 1, 1);
    //TQWidget *seekingWidget = new TQWidget (bbox);
    TQHBoxLayout *seekLayout = new TQHBoxLayout (bbox);
    seekLayout->addWidget(new TQLabel(i18n("Forward/backward seek time:"),bbox));
    seekLayout->addItem(new TQSpacerItem(0,0,TQSizePolicy::Minimum, TQSizePolicy::Minimum));
    seekTime = new TQSpinBox(1, 600, 1, bbox);
    seekLayout->addWidget(seekTime);
    seekLayout->addItem(new TQSpacerItem(0,0,TQSizePolicy::Minimum, TQSizePolicy::Minimum));
    gridlayout->addMultiCellLayout (seekLayout, 2, 2, 0, 1);

    layout->addWidget (windowbox);
    layout->addWidget (playbox);
    layout->addWidget (gbox);
    //layout->addWidget(autoHideSlider);
    layout->addItem (new TQSpacerItem (0, 0, TQSizePolicy::Minimum, TQSizePolicy::Expanding));
}

KDE_NO_CDTOR_EXPORT PrefGeneralPageLooks::PrefGeneralPageLooks (TQWidget *parent, Settings * settings)
 : TQFrame (parent, "LooksPage"),
   colors (settings->colors),
   fonts (settings->fonts) {
    TQVBoxLayout *layout = new TQVBoxLayout(this, 5, 2);

    TQGroupBox *colorbox= new TQGroupBox(2, TQt::Horizontal, i18n("Colors"), this);
    colorscombo = new TQComboBox (colorbox);
    for (int i = 0; i < int (ColorSetting::last_target); i++)
        colorscombo->insertItem (colors[i].title);
    colorscombo->setCurrentItem (0);
    connect (colorscombo, TQ_SIGNAL (activated (int)),
            this, TQ_SLOT (colorItemChanged(int)));
    colorbutton = new KColorButton (colorbox);
    colorbutton->setColor (colors[0].color);
    connect (colorbutton, TQ_SIGNAL (changed (const TQColor &)),
            this, TQ_SLOT (colorCanged (const TQColor &)));

    TQGroupBox *fontbox = new TQGroupBox (2,TQt::Horizontal, i18n ("Fonts"), this);
    fontscombo = new TQComboBox (fontbox);
    for (int i = 0; i < int (FontSetting::last_target); i++)
        fontscombo->insertItem (fonts[i].title);
    fontscombo->setCurrentItem (0);
    connect (fontscombo, TQ_SIGNAL (activated (int)),
            this, TQ_SLOT (fontItemChanged(int)));
    fontbutton = new TQPushButton (i18n ("AaBbCc"), fontbox);
    fontbutton->setFlat (true);
    fontbutton->setFont (fonts[0].font);
    connect (fontbutton, TQ_SIGNAL (clicked ()), this, TQ_SLOT (fontClicked ()));

    layout->addWidget (colorbox);
    layout->addWidget (fontbox);
    layout->addItem (new TQSpacerItem (0, 0, TQSizePolicy::Minimum, TQSizePolicy::Expanding));
}

KDE_NO_EXPORT void PrefGeneralPageLooks::colorItemChanged (int c) {
    if (c < int (ColorSetting::last_target))
        colorbutton->setColor (colors[c].newcolor);
}

KDE_NO_EXPORT void PrefGeneralPageLooks::colorCanged (const TQColor & c) {
    if (colorscombo->currentItem () < int (ColorSetting::last_target))
        colors[colorscombo->currentItem ()].newcolor = c;
}

KDE_NO_EXPORT void PrefGeneralPageLooks::fontItemChanged (int f) {
    if (f < int (FontSetting::last_target))
        fontbutton->setFont (fonts[f].newfont);
}

KDE_NO_EXPORT void PrefGeneralPageLooks::fontClicked () {
    if (fontscombo->currentItem () < int (FontSetting::last_target)) {
        TQFont myfont = fonts [fontscombo->currentItem ()].newfont;
        int res = TDEFontDialog::getFont (myfont, false, this);
        if (res == TDEFontDialog::Accepted) {
            fonts [fontscombo->currentItem ()].newfont = myfont;
            fontbutton->setFont (myfont);
        }
    }
}

KDE_NO_CDTOR_EXPORT PrefSourcePageURL::PrefSourcePageURL (TQWidget *parent)
: TQFrame (parent, "URLPage")
{
    TQVBoxLayout *layout = new TQVBoxLayout (this, 5, 5);
    TQHBoxLayout * urllayout = new TQHBoxLayout ();
    TQHBoxLayout * sub_urllayout = new TQHBoxLayout ();
    TQLabel *urlLabel = new TQLabel (i18n ("Location:"), this, 0);
    urllist = new KComboBox (true, this);
    urllist->setMaxCount (20);
    urllist->setDuplicatesEnabled (false); // not that it helps much :(
    url = new KURLRequester (urllist, this);
    TQWhatsThis::add (url, i18n ("Location of the playable item"));
    //url->setShowLocalProtocol (true);
    url->setSizePolicy (TQSizePolicy (TQSizePolicy::Expanding, TQSizePolicy::Preferred));
    TQLabel *sub_urlLabel = new TQLabel (i18n ("Sub title:"), this, 0);
    sub_urllist = new KComboBox (true, this);
    sub_urllist->setMaxCount (20);
    sub_urllist->setDuplicatesEnabled (false); // not that it helps much :(
    sub_url = new KURLRequester (sub_urllist, this);
    TQWhatsThis::add (sub_url, i18n ("Optional location of a file containing the subtitles of the URL above"));
    sub_url->setSizePolicy (TQSizePolicy (TQSizePolicy::Expanding, TQSizePolicy::Preferred));
    backend = new TQListBox (this);
    allowhref = new TQCheckBox (i18n ("Enable 'Click to Play' support"), this);
    TQWhatsThis::add (allowhref, i18n ("Support for WEB pages having a start image"));
    layout->addWidget (allowhref);
    urllayout->addWidget (urlLabel);
    urllayout->addWidget (url);
    layout->addLayout (urllayout);
    sub_urllayout->addWidget (sub_urlLabel);
    sub_urllayout->addWidget (sub_url);
    layout->addLayout (sub_urllayout);
    layout->addItem (new TQSpacerItem (0, 10, TQSizePolicy::Minimum, TQSizePolicy::Minimum));
    TQGridLayout * gridlayout = new TQGridLayout (2, 2);
    TQLabel *backendLabel = new TQLabel (i18n ("Use movie player:"), this, 0);
    //TQWhatsThis::add (allowhref, i18n ("Explain this in a few lines"));
    gridlayout->addWidget (backendLabel, 0, 0);
    gridlayout->addWidget (backend, 1, 0);
    gridlayout->addMultiCell (new TQSpacerItem (0, 0, TQSizePolicy::Expanding, TQSizePolicy::Minimum), 0, 1, 1, 1);
    TQGroupBox *cbox = new TQGroupBox(1, TQt::Vertical, i18n("Network bandwidth"), this);
    TQWidget * wbox = new TQWidget (cbox);
    TQGridLayout * bitratelayout = new TQGridLayout (wbox, 2, 3, 5);
    prefBitRate = new TQLineEdit (wbox);
    TQWhatsThis::add (prefBitRate, i18n("Sometimes it is possible to choose between various streams given a particular bitrate.\nThis option sets how much bandwidth you would prefer to allocate to video."));
    maxBitRate = new TQLineEdit (wbox);
    TQWhatsThis::add (maxBitRate, i18n("Sometimes it is possible to choose between various streams given a particular bitrate.\nThis option sets the maximum bandwidth you have available for video."));
    bitratelayout->addWidget(new TQLabel(i18n("Preferred bitrate:"), wbox), 0, 0);
    bitratelayout->addWidget (prefBitRate, 0, 1);
    bitratelayout->addWidget (new TQLabel (i18n ("kbit/s"), wbox), 0, 2);
    bitratelayout->addWidget (new TQLabel(i18n("Maximum bitrate:"), wbox), 1, 0);
    bitratelayout->addWidget (maxBitRate, 1, 1);
    bitratelayout->addWidget (new TQLabel (i18n ("kbit/s"), wbox), 1, 2);
    layout->addLayout (gridlayout);
    layout->addWidget (cbox);
    layout->addItem (new TQSpacerItem (0, 0, TQSizePolicy::Minimum, TQSizePolicy::Expanding));
    connect (urllist, TQ_SIGNAL(textChanged (const TQString &)),
             this, TQ_SLOT (slotTextChanged (const TQString &)));
    connect (sub_urllist, TQ_SIGNAL(textChanged (const TQString &)),
             this, TQ_SLOT (slotTextChanged (const TQString &)));
}

KDE_NO_EXPORT void PrefSourcePageURL::slotBrowse () {
}

KDE_NO_EXPORT void PrefSourcePageURL::slotTextChanged (const TQString &) {
    changed = true;
}

KDE_NO_CDTOR_EXPORT PrefRecordPage::PrefRecordPage (TQWidget *parent, PartBase * player, RecorderPage * rl, int rec_len) : TQFrame (parent, "RecordPage"), m_player (player), m_recorders (rl), m_recorders_length (rec_len) {
    TQVBoxLayout *layout = new TQVBoxLayout (this, 5, 5);
    TQHBoxLayout * urllayout = new TQHBoxLayout ();
    TQLabel *urlLabel = new TQLabel (i18n ("Output file:"), this);
    url = new KURLRequester ("", this);
    url->setShowLocalProtocol (true);
    urllayout->addWidget (urlLabel);
    urllayout->addWidget (url);
    recordButton = new TQPushButton (i18n ("Start &Recording"), this);
    connect (recordButton, TQ_SIGNAL (clicked ()), this, TQ_SLOT (slotRecord ()));
    TQHBoxLayout *buttonlayout = new TQHBoxLayout;
    buttonlayout->addItem (new TQSpacerItem (0, 0, TQSizePolicy::Minimum, TQSizePolicy::Minimum));
    buttonlayout->addWidget (recordButton);
    source = new TQLabel (i18n ("Current source: ") + m_player->source ()->prettyName (), this);
    recorder = new TQButtonGroup (m_recorders_length, TQt::Vertical, i18n ("Recorder"), this);
    for (RecorderPage * p = m_recorders; p; p = p->next)
        new TQRadioButton (p->name (), recorder);
    if (m_player->source ())
        sourceChanged (0L, m_player->source ());
    recorder->setButton(0); // for now
    replay = new TQButtonGroup (4, TQt::Vertical, i18n ("Auto Playback"), this);
    new TQRadioButton (i18n ("&No"), replay);
    new TQRadioButton (i18n ("&When recording finished"), replay);
    new TQRadioButton (i18n ("A&fter"), replay);
    TQWidget * customreplay = new TQWidget (replay);
    replaytime = new TQLineEdit (customreplay);
    TQHBoxLayout *replaylayout = new TQHBoxLayout (customreplay);
    replaylayout->addWidget (new TQLabel (i18n("Time (seconds):"), customreplay));
    replaylayout->addWidget (replaytime);
    replaylayout->addItem (new TQSpacerItem (0, 0, TQSizePolicy::Expanding, TQSizePolicy::Minimum));
    layout->addWidget (source);
    layout->addItem (new TQSpacerItem (5, 0, TQSizePolicy::Minimum, TQSizePolicy::Minimum));
    layout->addLayout (urllayout);
    layout->addItem (new TQSpacerItem (5, 0, TQSizePolicy::Minimum, TQSizePolicy::Minimum));
    layout->addWidget (recorder);
    layout->addItem (new TQSpacerItem (5, 0, TQSizePolicy::Minimum, TQSizePolicy::Minimum));
    layout->addWidget (replay);
    layout->addItem (new TQSpacerItem (5, 0, TQSizePolicy::Minimum, TQSizePolicy::Minimum));
    layout->addLayout (buttonlayout);
    layout->addItem (new TQSpacerItem (5, 0, TQSizePolicy::Minimum, TQSizePolicy::Expanding));
    connect (m_player, TQ_SIGNAL (sourceChanged(KMPlayer::Source*,KMPlayer::Source*)), this, TQ_SLOT (sourceChanged(KMPlayer::Source*,KMPlayer::Source*)));
    connect (recorder, TQ_SIGNAL (clicked(int)), this, TQ_SLOT(recorderClicked(int)));
    connect (replay, TQ_SIGNAL (clicked (int)), this, TQ_SLOT (replayClicked (int)));
}

KDE_NO_EXPORT void PrefRecordPage::recordingStarted () {
    recordButton->setText (i18n ("Stop Recording"));
    url->setEnabled (false);
    topLevelWidget ()->hide ();
}

KDE_NO_EXPORT void PrefRecordPage::recordingFinished () {
    recordButton->setText (i18n ("Start Recording"));
    url->setEnabled (true);
    TQTimer::singleShot (0, m_player, TQ_SLOT(recordingStopped())); // removed from PartBase::setSource because PartBase::recordingStopped calls openURL and that will call PartBase::setSource and TQt doesn't like disconnecting/connecting a signal that is current
}

KDE_NO_EXPORT void PrefRecordPage::sourceChanged (Source * olds, Source * nws) {
    int id = 0;
    int nr_recs = 0;
    if (olds) {
        disconnect(nws,TQ_SIGNAL(startRecording()),this, TQ_SLOT(recordingStarted()));
        disconnect(nws,TQ_SIGNAL(stopRecording()),this, TQ_SLOT(recordingFinished()));
    }
    if (nws) {
        for (RecorderPage * p = m_recorders; p; p = p->next, ++id) {
            TQButton * radio = recorder->find (id);
            bool b = m_player->recorders () [p->recorderName ()]->supports (nws->name ());
            radio->setEnabled (b);
            if (b) nr_recs++;
        }
        source->setText (i18n ("Current Source: ") + nws->prettyName ());
        connect (nws, TQ_SIGNAL(startRecording()), this, TQ_SLOT(recordingStarted()));
        connect (nws, TQ_SIGNAL(stopRecording()), this, TQ_SLOT(recordingFinished()));
    }
    recordButton->setEnabled (nr_recs > 0);
}

KDE_NO_EXPORT void PrefRecordPage::recorderClicked (int id) {
    bool b = false;
    TQButton *recBtn = recorder->find(id);
    if (recBtn)
    {
       b = recBtn->text().find (TQString::fromLatin1("Xine")) > -1;
    }
    replay->setEnabled (!b);
    if (b)
        replay->setButton (Settings::ReplayNo);

}

KDE_NO_EXPORT void PrefRecordPage::replayClicked (int id) {
    replaytime->setEnabled (id == Settings::ReplayAfter);
}

KDE_NO_EXPORT void PrefRecordPage::slotRecord () {
    connect (m_player->source (), TQ_SIGNAL (stopPlaying ()),
             this, TQ_SLOT (playingStopped ()));
    if (m_player->process () && m_player->process ()->playing ())
        m_player->process ()->quit ();
    else
        playingStopped ();
}

KDE_NO_EXPORT void PrefRecordPage::playingStopped () {
    disconnect (m_player->source (), TQ_SIGNAL (stopPlaying ()),
                this, TQ_SLOT (playingStopped ()));
    if (!url->lineEdit()->text().isEmpty()) {
        m_player->settings ()->recordfile = url->lineEdit()->text();
        m_player->settings ()->replaytime = replaytime->text ().toInt ();
#if KDE_IS_VERSION(3,1,90)
        int id = recorder->selectedId ();
        int replayid = replay->selectedId ();
#else
        int id = recorder->id (recorder->selected ());
        int replayid = replay->id (replay->selectedId ());
#endif
        m_player->settings ()->recorder = Settings::Recorder (id);
        m_player->settings ()->replayoption = Settings::ReplayOption (replayid);
        for (RecorderPage * p = m_recorders; p; p = p->next)
            if (id-- == 0) {
                p->record ();
                break;
            }
    }
}

KDE_NO_CDTOR_EXPORT RecorderPage::RecorderPage (TQWidget *parent, PartBase * player)
 : TQFrame (parent), next (0L), m_player (player) {}

KDE_NO_EXPORT void RecorderPage::record () {
    Process * proc = m_player->recorders () [recorderName ()];
    m_player->setRecorder (recorderName ());
    Recorder * rec = dynamic_cast <Recorder *> (proc);
    if (!proc->playing ()) {
        if (m_player->process ())
            m_player->process ()->quit ();
        rec->setURL (KURL (m_player->settings ()->recordfile));
        proc->setSource (m_player->source ());
        proc->ready (0L);
    } else {
        rec->setURL (KURL ());
        proc->stop ();
    }
}

KDE_NO_CDTOR_EXPORT PrefMEncoderPage::PrefMEncoderPage (TQWidget *parent, PartBase * player) : RecorderPage (parent, player) {
    TQVBoxLayout *layout = new TQVBoxLayout (this, 5, 5);
    format = new TQButtonGroup (3, TQt::Vertical, i18n ("Format"), this);
    new TQRadioButton (i18n ("Same as source"), format);
    new TQRadioButton (i18n ("Custom"), format);
    TQWidget * customopts = new TQWidget (format);
    TQGridLayout *gridlayout = new TQGridLayout (customopts, 1, 2, 2);
    TQLabel *argLabel = new TQLabel (i18n("Mencoder arguments:"), customopts, 0);
    arguments = new TQLineEdit ("", customopts);
    gridlayout->addWidget (argLabel, 0, 0);
    gridlayout->addWidget (arguments, 0, 1);
    layout->addWidget (format);
    layout->addItem (new TQSpacerItem (0, 0, TQSizePolicy::Minimum, TQSizePolicy::Expanding));
    connect (format, TQ_SIGNAL (clicked (int)), this, TQ_SLOT (formatClicked (int)));
}

KDE_NO_EXPORT void PrefMEncoderPage::formatClicked (int id) {
    arguments->setEnabled (!!id);
}

KDE_NO_EXPORT void PrefMEncoderPage::record () {
#if KDE_IS_VERSION(3,1,90)
    m_player->settings ()->recordcopy = !format->selectedId ();
#else
    m_player->settings ()->recordcopy = !format->id (format->selected ());
#endif
    m_player->settings ()->mencoderarguments = arguments->text ();
    RecorderPage::record ();
}

KDE_NO_EXPORT TQString PrefMEncoderPage::name () {
    return i18n ("&MEncoder");
}

KDE_NO_CDTOR_EXPORT PrefMPlayerDumpstreamPage::PrefMPlayerDumpstreamPage (TQWidget *parent, PartBase * player) : RecorderPage (parent, player) {
    hide();
}

KDE_NO_EXPORT TQString PrefMPlayerDumpstreamPage::name () {
    return i18n ("MPlayer -&dumpstream");
}

KDE_NO_CDTOR_EXPORT PrefFFMpegPage::PrefFFMpegPage (TQWidget *parent, PartBase * player) : RecorderPage (parent, player) {
    TQVBoxLayout *layout = new TQVBoxLayout (this, 5, 5);
    TQGridLayout *gridlayout = new TQGridLayout (1, 2, 2);
    TQLabel *argLabel = new TQLabel (i18n("FFMpeg arguments:"), this);
    arguments = new TQLineEdit ("", this);
    gridlayout->addWidget (argLabel, 0, 0);
    gridlayout->addWidget (arguments, 0, 1);
    layout->addLayout (gridlayout);
    layout->addItem (new TQSpacerItem (0, 0, TQSizePolicy::Minimum, TQSizePolicy::Expanding));
}

KDE_NO_EXPORT void PrefFFMpegPage::record () {
    m_player->settings ()->ffmpegarguments = arguments->text ();
    RecorderPage::record ();
}

KDE_NO_EXPORT TQString PrefFFMpegPage::name () {
    return i18n ("&FFMpeg");
}

#ifdef HAVE_XINE
KDE_NO_CDTOR_EXPORT PrefXinePage::PrefXinePage (TQWidget *parent, PartBase * player) : RecorderPage (parent, player) {
    hide();
}

KDE_NO_EXPORT TQString PrefXinePage::name () {
    return i18n ("&Xine");
}
#endif

KDE_NO_CDTOR_EXPORT PrefGeneralPageOutput::PrefGeneralPageOutput(TQWidget *parent, OutputDriver * ad, OutputDriver * vd)
 : TQFrame (parent) {
    TQGridLayout *layout = new TQGridLayout (this, 2, 2, 5);

    videoDriver = new TQListBox (this);
    for (int i = 0; vd[i].driver; i++)
        videoDriver->insertItem (vd[i].description, i);
    TQWhatsThis::add(videoDriver, i18n("Sets video driver. Recommended is XVideo, or, if it is not supported, X11, which is slower."));
    layout->addWidget (new TQLabel (i18n ("Video driver:"), this), 0, 0);
    layout->addWidget (videoDriver, 1, 0);

    audioDriver = new TQListBox (this);
    for (int i = 0; ad[i].driver; i++)
        audioDriver->insertItem (ad[i].description, i);
    layout->addWidget (new TQLabel (i18n ("Audio driver:"), this), 0, 1);
    layout->addWidget (audioDriver, 1, 1);
    layout->addItem (new TQSpacerItem (0, 0, TQSizePolicy::Minimum, TQSizePolicy::Expanding));
}

KDE_NO_CDTOR_EXPORT PrefOPPageGeneral::PrefOPPageGeneral(TQWidget *parent)
: TQFrame(parent)
{
    TQVBoxLayout *layout = new TQVBoxLayout (this, 5);
    layout->setAutoAdd (true);
}

KDE_NO_CDTOR_EXPORT PrefOPPagePostProc::PrefOPPagePostProc(TQWidget *parent) : TQFrame(parent)
{
    TQVBoxLayout *tabLayout = new TQVBoxLayout (this, 5);
    postProcessing = new TQCheckBox (i18n ("Enable use of postprocessing filters"), this);
    postProcessing->setEnabled( true );
    disablePPauto = new TQCheckBox (i18n ("Disable use of postprocessing when watching TV/DVD"), this);

    tabLayout->addWidget( postProcessing );
    tabLayout->addWidget( disablePPauto );
    tabLayout->addItem ( new TQSpacerItem( 5, 5, TQSizePolicy::Minimum, TQSizePolicy::Minimum ) );

    PostprocessingOptions = new TQTabWidget( this, "PostprocessingOptions" );
    PostprocessingOptions->setEnabled (true);
    PostprocessingOptions->setAutoMask (false);
    PostprocessingOptions->setTabPosition( TQTabWidget::Top );
    PostprocessingOptions->setTabShape( TQTabWidget::Rounded );
    PostprocessingOptions->setSizePolicy( TQSizePolicy( (TQSizePolicy::SizeType)1, (TQSizePolicy::SizeType)1, PostprocessingOptions->sizePolicy().hasHeightForWidth() ) );

    TQWidget *presetSelectionWidget = new TQWidget( PostprocessingOptions, "presetSelectionWidget" );
    TQGridLayout *presetSelectionWidgetLayout = new TQGridLayout( presetSelectionWidget, 1, 1, 1);

    TQButtonGroup *presetSelection = new TQButtonGroup(3, TQt::Vertical, presetSelectionWidget);
    presetSelection->setInsideSpacing(KDialog::spacingHint());

    defaultPreset = new TQRadioButton (i18n ("Default"), presetSelection);
    defaultPreset->setChecked( true );
    presetSelection->insert (defaultPreset);

    customPreset = new TQRadioButton (i18n ("Custom"), presetSelection);
    presetSelection->insert (customPreset);

    fastPreset = new TQRadioButton (i18n ("Fast"), presetSelection);
    presetSelection->insert (fastPreset);
    presetSelection->setRadioButtonExclusive ( true);
    presetSelectionWidgetLayout->addWidget( presetSelection, 0, 0 );
    PostprocessingOptions->insertTab( presetSelectionWidget, "" );

    //
    // SECOND!!!
    //
    /* I JUST WASN'T ABLE TO GET THIS WORKING WITH TQGridLayouts */

    TQWidget *customFiltersWidget = new TQWidget( PostprocessingOptions, "customFiltersWidget" );
    TQVBoxLayout *customFiltersWidgetLayout = new TQVBoxLayout( customFiltersWidget );

    TQGroupBox *customFilters = new TQGroupBox(0, TQt::Vertical, customFiltersWidget, "customFilters" );
    customFilters->setSizePolicy(TQSizePolicy((TQSizePolicy::SizeType)1, (TQSizePolicy::SizeType)2));
    customFilters->setFlat(false);
    customFilters->setEnabled( false );
    customFilters->setInsideSpacing(7);

    TQLayout *customFiltersLayout = customFilters->layout();
    TQHBoxLayout *customFiltersLayout1 = new TQHBoxLayout ( customFilters->layout() );

    HzDeblockFilter = new TQCheckBox (i18n ("Horizontal deblocking"), customFilters);
    HzDeblockAQuality = new TQCheckBox (i18n ("Auto quality"), customFilters);
    HzDeblockAQuality->setEnabled (false);
    HzDeblockCFiltering = new TQCheckBox (i18n ("Chrominance filtering"), customFilters);
    HzDeblockCFiltering->setEnabled (false);

    customFiltersLayout1->addWidget( HzDeblockFilter );
    customFiltersLayout1->addItem( new TQSpacerItem( 0, 0, TQSizePolicy::Minimum, TQSizePolicy::Minimum ) );
    customFiltersLayout1->addWidget( HzDeblockAQuality );
    customFiltersLayout1->addWidget( HzDeblockCFiltering );

    TQFrame *line1 = new TQFrame( customFilters, "line1" );
    line1->setSizePolicy( TQSizePolicy( (TQSizePolicy::SizeType)1, (TQSizePolicy::SizeType)2 ) );
    line1->setFrameShape( TQFrame::HLine );
    line1->setFrameShadow( TQFrame::Sunken );
    customFiltersLayout->add(line1);

    TQHBoxLayout *customFiltersLayout2 = new TQHBoxLayout ( customFilters->layout() );

    VtDeblockFilter = new TQCheckBox(i18n("Vertical deblocking"), customFilters);
    VtDeblockAQuality = new TQCheckBox (i18n ("Auto quality"), customFilters);
    VtDeblockAQuality->setEnabled (false);
    VtDeblockCFiltering = new TQCheckBox (i18n ("Chrominance filtering"), customFilters);
    VtDeblockCFiltering->setEnabled (false);

    customFiltersLayout2->addWidget( VtDeblockFilter );
    customFiltersLayout2->addItem( new TQSpacerItem( 0, 0, TQSizePolicy::Minimum, TQSizePolicy::Minimum ) );
    customFiltersLayout2->addWidget( VtDeblockAQuality );
    customFiltersLayout2->addWidget( VtDeblockCFiltering );

    TQFrame *line2 = new TQFrame( customFilters, "line2" );

    line2->setSizePolicy( TQSizePolicy( (TQSizePolicy::SizeType)1, (TQSizePolicy::SizeType)2 ) );
    line2->setFrameShape( TQFrame::HLine );
    line2->setFrameShadow( TQFrame::Sunken );
    customFiltersLayout->add(line2);

    TQHBoxLayout *customFiltersLayout3  = new TQHBoxLayout ( customFilters->layout() );

    DeringFilter = new TQCheckBox (i18n ("Dering filter"), customFilters);
    DeringAQuality = new TQCheckBox (i18n ("Auto quality"), customFilters);
    DeringAQuality->setEnabled (false);
    DeringCFiltering=new TQCheckBox(i18n("Chrominance filtering"),customFilters);
    DeringCFiltering->setEnabled (false);

    customFiltersLayout3->addWidget( DeringFilter );
    customFiltersLayout3->addItem( new TQSpacerItem( 0, 0, TQSizePolicy::Minimum, TQSizePolicy::Minimum ) );
    customFiltersLayout3->addWidget( DeringAQuality );
    customFiltersLayout3->addWidget( DeringCFiltering );

    TQFrame *line3 = new TQFrame( customFilters, "line3" );
    line3->setFrameShape( TQFrame::HLine );
    line3->setFrameShadow( TQFrame::Sunken );
    line3->setFrameShape( TQFrame::HLine );

    customFiltersLayout->add(line3);

    TQHBoxLayout *customFiltersLayout4 =new TQHBoxLayout(customFilters->layout());

    AutolevelsFilter = new TQCheckBox (i18n ("Auto brightness/contrast"), customFilters);
    AutolevelsFullrange = new TQCheckBox (i18n ("Stretch luminance to full range"), customFilters);
    AutolevelsFullrange->setEnabled (false);

    customFiltersLayout4->addWidget(AutolevelsFilter);
    customFiltersLayout4->addItem(new TQSpacerItem( 0, 0, TQSizePolicy::Minimum, TQSizePolicy::Minimum ));
    customFiltersLayout4->addWidget(AutolevelsFullrange);

    TQHBoxLayout *customFiltersLayout5 = new TQHBoxLayout (customFilters->layout());

    TmpNoiseFilter =new TQCheckBox(i18n("Temporal noise reducer"),customFilters);
    /*	Note: Change TmpNoiseFilter text back to "Label:" if this slider gets reactivated
        TmpNoiseSlider = new TQSlider( customFilters, "TmpNoiseSlider" );
        TmpNoiseSlider->setEnabled( false );
        TmpNoiseSlider->setMinValue( 1 );
        TmpNoiseSlider->setMaxValue( 3 );
        TmpNoiseSlider->setValue( 1 );
        TmpNoiseSlider->setOrientation( TQSlider::Horizontal );
        TmpNoiseSlider->setTickmarks( TQSlider::Left );
        TmpNoiseSlider->setTickInterval( 1 );
        TmpNoiseSlider->setSizePolicy(TQSizePolicy( (TQSizePolicy::SizeType)1, (TQSizePolicy::SizeType)1));*/

    /*customFiltersLayout->addWidget(TmpNoiseFilter,7,0);
      customFiltersLayout->addWidget(TmpNoiseSlider,7,2);*/
    customFiltersLayout5->addWidget(TmpNoiseFilter);
    customFiltersLayout5->addItem(new TQSpacerItem( 0, 0, TQSizePolicy::Minimum, TQSizePolicy::Minimum ));
    //customFiltersLayout5->addWidget(TmpNoiseSlider);
    customFiltersWidgetLayout->addWidget( customFilters );
    PostprocessingOptions->insertTab( customFiltersWidget, "" );
    //
    //THIRD!!!
    //
    TQWidget *deintSelectionWidget = new TQWidget( PostprocessingOptions, "deintSelectionWidget" );
    TQVBoxLayout *deintSelectionWidgetLayout = new TQVBoxLayout( deintSelectionWidget);
    TQButtonGroup *deinterlacingGroup = new TQButtonGroup(5, TQt::Vertical, deintSelectionWidget, "deinterlacingGroup" );

    LinBlendDeinterlacer = new TQCheckBox (i18n ("Linear blend deinterlacer"), deinterlacingGroup);
    LinIntDeinterlacer = new TQCheckBox (i18n ("Linear interpolating deinterlacer"), deinterlacingGroup);
    CubicIntDeinterlacer = new TQCheckBox (i18n ("Cubic interpolating deinterlacer"), deinterlacingGroup);
    MedianDeinterlacer = new TQCheckBox (i18n ("Median deinterlacer"), deinterlacingGroup);
    FfmpegDeinterlacer = new TQCheckBox (i18n ("FFmpeg deinterlacer"), deinterlacingGroup);

    deinterlacingGroup->insert( LinBlendDeinterlacer );
    deinterlacingGroup->insert( LinIntDeinterlacer );
    deinterlacingGroup->insert( CubicIntDeinterlacer );
    deinterlacingGroup->insert( MedianDeinterlacer );
    deinterlacingGroup->insert( FfmpegDeinterlacer );

    deintSelectionWidgetLayout->addWidget( deinterlacingGroup, 0, 0 );

    PostprocessingOptions->insertTab( deintSelectionWidget, "" );

    tabLayout->addWidget( PostprocessingOptions/*, 1, 0*/ );

    PostprocessingOptions->setEnabled(false);
    connect( customPreset, TQ_SIGNAL (toggled(bool) ), customFilters, TQ_SLOT(setEnabled(bool)));
    connect( postProcessing, TQ_SIGNAL( toggled(bool) ), PostprocessingOptions, TQ_SLOT( setEnabled(bool) ) );
    connect( HzDeblockFilter, TQ_SIGNAL( toggled(bool) ), HzDeblockAQuality, TQ_SLOT( setEnabled(bool) ) );
    connect( HzDeblockFilter, TQ_SIGNAL( toggled(bool) ), HzDeblockCFiltering, TQ_SLOT( setEnabled(bool) ) );
    connect( VtDeblockFilter, TQ_SIGNAL( toggled(bool) ), VtDeblockCFiltering, TQ_SLOT( setEnabled(bool) ) );
    connect( VtDeblockFilter, TQ_SIGNAL( toggled(bool) ), VtDeblockAQuality, TQ_SLOT( setEnabled(bool) ) );
    connect( DeringFilter, TQ_SIGNAL( toggled(bool) ), DeringAQuality, TQ_SLOT( setEnabled(bool) ) );
    connect( DeringFilter, TQ_SIGNAL( toggled(bool) ), DeringCFiltering, TQ_SLOT( setEnabled(bool) ) );
    //connect( TmpNoiseFilter, TQ_SIGNAL( toggled(bool) ), TmpNoiseSlider, TQ_SLOT( setEnabled(bool) ) );

    connect( AutolevelsFilter, TQ_SIGNAL( toggled(bool) ), AutolevelsFullrange, TQ_SLOT( setEnabled(bool) ) );

    TQWhatsThis::add( defaultPreset, i18n( "Enable mplayer's default postprocessing filters" ) );
    TQWhatsThis::add( customPreset, i18n( "Enable custom postprocessing filters (See: Custom preset -tab)" ) );
    TQWhatsThis::add( fastPreset, i18n( "Enable mplayer's fast postprocessing filters" ) );
    PostprocessingOptions->changeTab( presetSelectionWidget, i18n( "General" ) );
    customFilters->setTitle (TQString ());
    TQWhatsThis::add( HzDeblockAQuality, i18n( "Filter is used if there is enough CPU" ) );
    TQWhatsThis::add( VtDeblockAQuality, i18n( "Filter is used if there is enough CPU" ) );
    TQWhatsThis::add( DeringAQuality, i18n( "Filter is used if there is enough CPU" ) );
    //TQWhatsThis::add( TmpNoiseSlider, i18n( "Strength of the noise reducer" ) );
    TQWhatsThis::add( AutolevelsFullrange, i18n( "Stretches luminance to full range (0..255)" ) );
    PostprocessingOptions->changeTab( customFiltersWidget, i18n( "Custom Preset" ) );
    deinterlacingGroup->setTitle (TQString ());
    PostprocessingOptions->changeTab( deintSelectionWidget, i18n( "Deinterlacing" ) );
    PostprocessingOptions->adjustSize();
}

KDE_NO_EXPORT void Preferences::confirmDefaults() {
	// TODO: Switch to KMessageBox
	switch( TQMessageBox::warning( this, i18n("Reset Settings?"),
        i18n("You are about to have all your settings overwritten with defaults.\nPlease confirm.\n"),
        i18n ("&OK"), i18n ("&Cancel"), TQString (), 0, 1)) {
    		case 0:	Preferences::setDefaults();
        		break;
    		case 1:	break;
	}

}

KDE_NO_EXPORT void Preferences::setDefaults() {
	m_GeneralPageGeneral->keepSizeRatio->setChecked(true);
	m_GeneralPageGeneral->loop->setChecked(false);
	m_GeneralPageGeneral->seekTime->setValue(10);

	m_GeneralPageOutput->videoDriver->setCurrentItem (0);
	m_GeneralPageOutput->audioDriver->setCurrentItem(0);

	m_OPPagePostproc->postProcessing->setChecked(false);
	m_OPPagePostproc->disablePPauto->setChecked(true);

	m_OPPagePostproc->defaultPreset->setChecked(true);

	m_OPPagePostproc->LinBlendDeinterlacer->setChecked(false);
	m_OPPagePostproc->LinIntDeinterlacer->setChecked(false);
	m_OPPagePostproc->CubicIntDeinterlacer->setChecked(false);
	m_OPPagePostproc->MedianDeinterlacer->setChecked(false);
	m_OPPagePostproc->FfmpegDeinterlacer->setChecked(false);

}
#include "pref.moc"