/***************************************************************************
 *   Copyright (C) 2004 by Marco Kraus                                     *
 *   marco@libsdl.de                                                       *
 *                                                                         *
 *   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.             *
 ***************************************************************************
$Id: konverterdialog.cpp,v 1.1.1.1 2005/06/24 13:18:30 marco Exp $
*/
#include <kconfig.h>
#include <kguiitem.h>
#include "konverterdialog.h"

KonverterDialog::KonverterDialog(QWidget* parent, const char* name, bool modal, WFlags fl)
: KonverterMainDialog(parent,name, modal,fl)
{
  OutputDirBox->insert(QDir::homeDirPath());  // default output directory for conversion
  JoinOutputDir->insert(QDir::homeDirPath());  // default output directory for concat

  running = false; // nothing is running at this point
  appendText = true;  // normally we want to append new text to the output

  // no options menu called
  MP3OptionsCheck = false;
  MP2OptionsCheck = false;
  AC3OptionsCheck = false;
  PCMOptionsCheck = false;
  NoOptionsCheck = false;

  DivXOptionsCheck = false;
  XvidOptionsCheck = false;
  MPEG2OptionsCheck = false;
  MPEG1OptionsCheck = false;
  DivXLavcOptionsCheck = false;
  RawOptionsCheck = false;

  SoundFiltersCheck = false;
  VideoFiltersCheck = false;

  withDivx3 = false;
  mencPass = 0;

  // update command box
  UpdateConversionCommandString();

  //load xine
  movInfo = new KXineWidget(this, "orXine", QString::null, QString::null, "none", "none", false, false);
  movInfo->hide();
  movInfo->initXine();

  //load working dialog
  workDlg = new workdlg(this, "workDlg");
  connect( workDlg->buttonCancel, SIGNAL(released()),this,SLOT(ExecWorkW()));

  //Configs
  KConfig &config = *KGlobal::config();
  config.setGroup("Window");
  resize(config.readSizeEntry("Size"));
  move(config.readPointEntry("Pos"));
  config.setGroup("Files");
  InputNameBox->setText(config.readEntry("InFile",""));
  OutputNameBox->setText(config.readEntry("OutFile",""));
  OutputDirBox->setText(config.readEntry("OutDir",QDir::homeDirPath()));
  config.setGroup("Options");
  PrefVerbCheckBox->setChecked(config.readBoolEntry("Verbose",false));
  PrAoDrBox->setCurrentText(config.readEntry("PrAoDriver","oss"));
  PrAoCheckBox->setChecked(config.readBoolEntry("PrAoBoth",false));
}

KonverterDialog::~KonverterDialog()
{
}

void KonverterDialog::ConvertFile()
{
     appendText = true;  // append any new text to output box

     if( running ){  // process is still running and user aborted
        mencoder->tryTerminate(); // trying the nice way...
        QTimer::singleShot( 3000, mencoder, SLOT( kill() ) );  // no reaction ? We'll try bazooka...
        workDlg->TextOutput->append( i18n("<h4><font color=red>conversion aborted</font></h4>") );
        running = false;
        appendText = false;  // do not append any new text to output box
    workDlg->doneworking("Conversion Aborted!");
     }else if ( QFile::exists( InputNameBox->text() ) == false ){
    workDlg->TextOutput->append( i18n("<h4><font color=red>Error: File not found: <b>" + InputNameBox->text() + "</b></font></h4>"));
    }else{
        workDlg->TextOutput->clear(); // clear textbox with every conversion
        running = true; // process is running
        if(mencPass == 0)
           workDlg->TextOutput->append(i18n("<font color=green><h4>Converting</h4></font>"));
    else
       workDlg->TextOutput->append(i18n("<font color=green><h4>Converting pass 1</h4></font>"));
        buttonConvert->setText(i18n("&Abort"));   // set abort button

    //Get directory
    QFileInfo fi(mencoder->inFile());
    dirPath= fi.dirPath(true);

    mencoder->setWorkingDirectory(dirPath);//sets working directory usefull for multipass encoding
        // connect the stdout/stderr output of mencoder to the textbox
        connect( mencoder, SIGNAL(readyReadStdout()),this, SLOT(readFromStdout()) );
    //verbose
    if (PrefVerbCheckBox->isChecked())
           connect( mencoder, SIGNAL(readyReadStderr()),this, SLOT(readFromStderr()) );
        connect( mencoder, SIGNAL(processExited()),this, SLOT(processExiting()) );

        // setup the progress bar
        workDlg->ProgressBar->setTotalSteps(100);   // set it to 100, because we grep the percentage
        ProgressIndicator = 0;
        workDlg->ProgressBar->setProgress(ProgressIndicator);

        mencoder->setDevNull(false); //resets usage of /dev/null
    if ( TwoPassCheckBox->isChecked())
    {
       workDlg->passworking(i18n("Converting in 2-pass ")+mencoder->inFile());
       mencoder->setDevNull(true);
    }
    else
       workDlg->working(i18n("Converting ")+mencoder->inFile());

    workDlg->TextOutput->append( "Out: " + mencoder->getCommand() );  // debug: show all option arguments
        workDlg->show();
        // start the mencoder process
        if (!(mencoder->start())) {
            workDlg->TextOutput->append( i18n("<h4><font color=red>Error: Failed to run mencoder.<br>Check if mplayer is installed and in your PATH.</font></h4>"));
        workDlg->errorworking();
    }
     }
}

void KonverterDialog::ConcatFile()
{
     appendText = true;  // append any new text to output box

     if( running ){  // process is still running and user aborted
        mencoder->tryTerminate(); // trying the nice way...
        QTimer::singleShot( 3000, mencoder, SLOT( kill() ) );  // no reaction ? We'll try bazooka...
        workDlg->TextOutput->append( i18n("<h4><font color=red>concat aborted</font></h4>") );
    workDlg->doneworking("Concat Aborted!");
        running = false;
        appendText = false;  // do not append any new text to output box
     }else{
        workDlg->TextOutput->clear(); // clear textbox with every conversion
        running = true; // process is running

        workDlg->TextOutput->append(i18n("<font color=green><h4>Concat files</h4></font>"));
        buttonConvert->setText(i18n("Abort"));   // set abort button

        // now set up the mencoder process
        mencoder = new KonvProcess();

        QStringList mencoderArgList = NULL;
        mencoderArgList = mencoderArgList.split( " ", mencoderString->text() ); // create StringList for arguments

    QString TempStr;
    for(uint i=0; i<JoinFilesBox->count(); i++)
           mencoderArgList.append( JoinFilesBox->item(i)->text());
        mencoder->setArguments( mencoderArgList );

        // connect the stdout/stderr output of mencoder to the textbox
        connect( mencoder, SIGNAL(readyReadStdout()),this, SLOT(readFromStdout()) );
    //verbose
    if (PrefVerbCheckBox->isChecked())
        connect( mencoder, SIGNAL(readyReadStderr()),this, SLOT(readFromStderr()) );
        connect( mencoder, SIGNAL(processExited()),this, SLOT(processExiting()) );

        // setup the progress bar
        workDlg->ProgressBar->setTotalSteps(100);   // set it to 100, because we grep the percentage
        ProgressIndicator = 0;
        workDlg->ProgressBar->setProgress(ProgressIndicator);

        // debug: output all mencoder arguments
        workDlg->TextOutput->append(mencoder->arguments().join(" "));  // debug: show all option arguments

    workDlg->working(i18n("Concating "));
        workDlg->show();
        // start the mencoder process
        if (!(mencoder->start())) {
            workDlg->TextOutput->append( i18n("<h4><font color=red>Error: Failed to run avimerge.<br>Check if transcode is installed and in your PATH.</font></h4>"));
        }
     }
}


void KonverterDialog::readFromStdout(){

    OutputLine = (QString)mencoder->readStdout();

    if(appendText)
    {
      if(OutputLine.contains('%')) // if percent incremented since last step
      {
       if(LastStatus != OutputLine.mid(21,2)){  // if percentage changed
           ProgressIndicator = LastStatus.toInt();
           if (ProgressIndicator != 0)
       {
           MBPos = OutputLine.find("mb");
           if ( OutputLine.mid(MBPos-4, 6).contains("mb") )
           {
              workDlg->EstSize->setText(i18n("Estimated")+" "+i18n("Size")+":"+OutputLine.mid(MBPos-4, 4)+i18n("Mb"));
           }
           MBPos = OutputLine.find("min");
           if ( OutputLine.mid(MBPos-4,7).contains("min") )
           {
              if ( OutputLine.mid(MBPos-4,4).toInt() != 0 )
                 workDlg->TimeLeft->setText(i18n("Time Left")+":"+OutputLine.mid(MBPos-4,4)+i18n("Min"));
          else
          {
             if ( ProgressIndicator < 3 )
                workDlg->TimeLeft->setText(i18n("Time Left")+": "+i18n("Unknown"));
             else
                workDlg->TimeLeft->setText(i18n("Time Left")+": "+i18n("Less than a minute"));
              }
           }
           if(mencPass == 1)
              workDlg->OverProgressBar->setProgress(ProgressIndicator/2);
           else if(mencPass ==2)
              workDlg->OverProgressBar->setProgress(ProgressIndicator/2+50);
               workDlg->ProgressBar->setProgress(ProgressIndicator);  // also increment progress bar
      }
     LastStatus = OutputLine.mid(21,2);
       }
      }
    }
}

bool KonverterDialog::processExiting(){
     std::cout << "progressExiting()" << std::endl;

        workDlg->ProgressBar->setProgress(100); // set to 100%

     if(appendText) {
          switch (mencoder->exitStatus()) {
               case 0:
              if( mencPass == 0 )
          {
                      workDlg->TextOutput->append( i18n("<h4><font color=green>Conversion done</font></h4>") );
              workDlg->doneworking("Done!");
           }
           else if (mencPass == 1)
           {
           mencPass=2;
           if(XvidOptionsCheck)
           {
              VideoOpts = XvidOpt->getOptions(mencPass);
           }
           else if (DivXLavcOptionsCheck)
           {
              VideoOpts = DivXLavcOpt->getOptions(mencPass);
           }
              mencoder->setDevNull(false);//dont use /dev/null
              mencoder->setWorkingDirectory(dirPath);//sets working directory usefull for multipass encoding
              UpdateConversionCommandString();
              workDlg->TextOutput->append(i18n("<font color=green><h4>Converting pass 2</h4></font>"));
              workDlg->TextOutput->append(mencoder->getCommand());
               connect( mencoder, SIGNAL(processExited()),this, SLOT(processExiting()) );
               connect( mencoder, SIGNAL(readyReadStdout()),this, SLOT(readFromStdout()) );
                //verbose
            if (PrefVerbCheckBox->isChecked())
                connect( mencoder, SIGNAL(readyReadStderr()),this, SLOT(readFromStderr()) );
                mencoder->start();
           }
           else
           {
              workDlg->OverProgressBar->setProgress(100);
              workDlg->TextOutput->append( i18n("<h4><font color=green>2-Pass conversion done</font></h4>") );
              workDlg->doneworking("Done!");
           }
                   break;
               case 1:
                    workDlg->TextOutput->append( i18n("<h4><font color=red>Mencoder returned an error.</font></h4>") );
            workDlg->errorworking();
                    break;
               case 139: //segmentation fault in mencoder
                    workDlg->TextOutput->append( i18n("<h4><font color=red>Mencoder crashed, sorry. Try again.</font></h4>") );
            workDlg->errorworking();
                    break;
          }
     }
     if (!(mencoder->isRunning()))
     {
        buttonConvert->setText(i18n("&Execute")); // reset convert button
        running = false; // no process is running
     }

  return true;
}

void KonverterDialog::scrollToTop(){
    workDlg->TextOutput->setContentsPos( 0, 0 );
}

void KonverterDialog::readFromStderr(){
   if(appendText)
      workDlg->TextOutput->append( mencoder->readStderr() );
}

void KonverterDialog::ExitKonverter()
{
//Saving Settings
  KConfig &config = *KGlobal::config();
  config.setGroup("Window");
  config.writeEntry("Size",size());
  config.writeEntry("Pos",pos());
  config.setGroup("Files");
  config.writeEntry("InFile",InputNameBox->text());
  config.writeEntry("OutFile",OutputNameBox->text());
  config.writeEntry("OutDir",OutputDirBox->text());
  config.setGroup("Options");
  config.writeEntry("Verbose",PrefVerbCheckBox->isChecked());
  config.writeEntry("PrAoDriver",PrAoDrBox->currentText());
  config.writeEntry("PrAoBoth",PrAoCheckBox->isChecked());
  config.sync();
  this->close();
}

void KonverterDialog::TabChanged()
{
   std::cout << "Tab changed to " << MainTabSelectBox->currentPage()->name() << std::endl;

   if(qstrcmp(MainTabSelectBox->currentPage()->name(),"ConversionPage") == 0){  // internal page-name comparision. Do NOT translate.
      UpdateConversionCommandString();
   }else if(qstrcmp(MainTabSelectBox->currentPage()->name(),"ConcatPage") == 0){
      UpdateConcatCommandString();
   }else if(qstrcmp(MainTabSelectBox->currentPage()->name(),"GrabbingPage") == 0){
      mencoderString->setText("grabbing");
   }else if(qstrcmp(MainTabSelectBox->currentPage()->name(),"ExtractionPage") == 0){
      mencoderString->setText("extract");
   }else if(qstrcmp(MainTabSelectBox->currentPage()->name(),"PreferencesPage") == 0){
      mencoderString->setText("preferences");
   }else if(qstrcmp(MainTabSelectBox->currentPage()->name(),"SplitPage") == 0){
      mencoderString->setText("Split");
      getSplitter();
   }
}

void KonverterDialog::SelectInputFile()
{
  static QString oldfnamedir = QDir::homeDirPath();
  QString fname = KFileDialog::getOpenFileName(oldfnamedir, i18n("Videos (*.mpeg *.mpg *.avi *.mov *.asf *.wmv);;all (*.*)"));
  if (fname != NULL) {
       InputNameBox->clear();
       InputNameBox->insert(fname);
       oldfnamedir = fname.section('/', 0, -2);
       ChangeMovInfo();
  }
}

void KonverterDialog::SelectOutputDirConcat()
{
  static QString olddirname = QDir::homeDirPath();
  QString dirname = KFileDialog::getExistingDirectory(olddirname);
  if (dirname != NULL) {
       JoinOutputDir->clear();
       JoinOutputDir->insert(dirname);
       olddirname = dirname;
  }
}

void KonverterDialog::SelectOutputDir()
{
  static QString olddirname = QDir::homeDirPath();
  QString dirname = KFileDialog::getExistingDirectory(olddirname);
  if (dirname != NULL) {
       OutputDirBox->clear();
       OutputDirBox->insert(dirname);
       olddirname = dirname;
  }
}

void KonverterDialog::RemoveJoinFile()
{
  JoinFilesBox->removeItem(JoinFilesBox->currentItem());
}

void KonverterDialog::SelectJoinFiles()
{
  static QString homedir = QDir::homeDirPath();
  QStringList JoinFiles = KFileDialog::getOpenFileNames(homedir, i18n("Videos (*.avi *.AVI)"));

  QStringList::Iterator it = JoinFiles.begin();
  while( it != JoinFiles.end() ) {
      QListBoxText* newBox = new QListBoxText(*it);
      JoinFilesBox->insertItem(newBox);
      ++it;
  }

  UpdateConcatCommandString(); // update command string window
}

void KonverterDialog::UpdateConversionCommandString()
{
  std::cout << "UpdateConversionCommandString()" << std::endl;

  // This code cleans up variables on codec change.
  static int oldVideoItem = OVFormatBox->currentItem();
  static int oldAudioItem = OAFormatBox->currentItem();

  if (OVFormatBox->currentItem() != oldVideoItem)
  {
     VideoOpts = "";
      oldVideoItem = OVFormatBox->currentItem();
  }

  if (OAFormatBox->currentItem() != oldAudioItem)
  {
     AudioOpts = "";
      oldAudioItem = OAFormatBox->currentItem();
  }

  // resolv codecs
  switch(OVFormatBox->currentItem()){
     case 0:
          VideoCodec = "copy";
          break;
     case 1:
          VideoCodec = "divx4";  // -div4opts should be set within the options tab
          break;
     case 2:
          VideoCodec = "xvid";
          break;
     case 3:
          VideoCodec = "lavc -lavcopts vcodec=mpeg2video";
          break;
     case 4:
          VideoCodec = "lavc -lavcopts vcodec=mpeg1video";
          break;
     case 5:
           if (withDivx3) VideoCodec = "lavc -lavcopts vcodec=msmpeg4";
            else VideoCodec = "lavc -lavcopts vcodec=mpeg4";
          break;
     case 6:
          VideoCodec = "libdv";
          break;
     default:
         break;
  }

  switch(OAFormatBox->currentItem()){
     case 0:
          AudioCodec = "copy";
          break;
     case 1:
          AudioCodec = "mp3lame"; // -lameopts should be set within the options tab
          break;
     case 2:
          AudioCodec = "pcm";
          break;
     case 3:
          AudioCodec = "lavc -lavcopts acodec=mp2";
          break;
     case 4:
          AudioCodec = "lavc -lavcopts acodec=ac3";
          break;
     default:
         break;
  }

  QString encoderCommand = NULL;
  encoderCommand = encoderCommand+"mencoder ";  // add mencoder binary
  encoderCommand = encoderCommand+"-ovc "+VideoCodec+VideoOpts+" ";  // add mencoder video codec
  encoderCommand = encoderCommand+"-oac "+AudioCodec+AudioOpts+AudioFilt+" ";  // add mencoder audio codec
  mencoder = new KonvProcess(); //If not created
  mencoder->setMencOpts( encoderCommand );
  mencoder->setInFile( InputNameBox->text() );
  mencoder->setOutFile( OutputDirBox->text()+"/"+OutputNameBox->text() );
  mencoderString->setText( mencoder->getCommand() );  // update mencoder command text-field
}

void KonverterDialog::UpdateConcatCommandString()
{
  std::cout << "UpdateConcatCommandString()" << std::endl;
  QString encoderCommand = NULL;

  encoderCommand = "avimerge";  // using avimerge from transcode

  if( JoinOutputDir->text().endsWith("/") ) // check for ending slash
     encoderCommand = encoderCommand+" -o "+JoinOutputDir->text()+JoinOutputName->text();  // add output filename
  else
     encoderCommand = encoderCommand+" -o "+JoinOutputDir->text()+"/"+JoinOutputName->text();  // add output filename

  encoderCommand = encoderCommand+" -i ";

  std::cout << "Anzahzl: " << JoinFilesBox->count() << std::endl;

  mencoderString->setText(encoderCommand);  // update mencoder command text-field
}

void KonverterDialog::ExecuteCommandString()
{
   if(qstrcmp(MainTabSelectBox->currentPage()->name(),"ConversionPage") == 0){  // internal page-name comparision. Do NOT translate.
      /*Those if's are needed to check if pressed convert or abort (madness ;) ) */
      if(buttonConvert->text() == i18n("&Execute")){
      if(!(checkConvert())){ //checks if conversion can be done
         ConvertFile();
      }}else ConvertFile();
   }else if(qstrcmp(MainTabSelectBox->currentPage()->name(),"ConcatPage") == 0){
      ConcatFile();
   }else if(qstrcmp(MainTabSelectBox->currentPage()->name(),"GrabbingPage") == 0){

   }else if(qstrcmp(MainTabSelectBox->currentPage()->name(),"ExtractionPage") == 0){

   }else if(qstrcmp(MainTabSelectBox->currentPage()->name(),"PreferencesPage") == 0){

   }else if(qstrcmp(MainTabSelectBox->currentPage()->name(),"SplitPage") == 0){
      SplitMovie();
   }
}

void KonverterDialog::ShowAboutDialog()
{
  AboutDialog* ad = new AboutDialog();
  ad->show();
}

void KonverterDialog::ShowVideoOptionsDialog()
{
  // resolv codecs
  switch(OVFormatBox->currentItem()){
     case 0:
          if(!NoOptionsCheck){
               noOpt = new NoOptDialog();  // only create if never done before
               NoOptionsCheck = true;
          }
          noOpt->show();
          break;
     case 1:
          if(!DivXOptionsCheck){
               DivXOpt = new DivXOptDialog();  // only create if never done before
               DivXOptionsCheck = true;
          }
          if (DivXOpt->exec())
            {
              VideoOpts = DivXOpt->getOptions();
              UpdateConversionCommandString();
            }
          break;
     case 2:
          if(!XvidOptionsCheck){
               XvidOpt = new XvidOptDialog();  // only create if never done before
               XvidOptionsCheck = true;
          }
          if (XvidOpt->exec())
            {
              VideoOpts = XvidOpt->getOptions(mencPass);
              UpdateConversionCommandString();
            }
          break;
     case 3:
          if(!MPEG2OptionsCheck){
               MPEG2Opt = new MPEG2OptDialog();  // only create if never done before
               MPEG2OptionsCheck = true;
          }
          if (MPEG2Opt->exec())
            {
              VideoOpts = MPEG2Opt->getOptions();
              UpdateConversionCommandString();
            }
          break;
     case 4:
          if(!MPEG1OptionsCheck){
               MPEG1Opt = new MPEG1OptDialog();  // only create if never done before
               MPEG1OptionsCheck = true;
          }
          if (MPEG1Opt->exec())
            {
              VideoOpts = MPEG1Opt->getOptions();
              UpdateConversionCommandString();
            }
          break;
     case 5:
               if(!DivXLavcOptionsCheck){
                    DivXLavcOpt = new DivXLavcOptDialog();  // only create if never done before
                    DivXLavcOptionsCheck = true;
               }
               if (DivXLavcOpt->exec())
               {
                    VideoOpts = DivXLavcOpt->getOptions(mencPass);
                    if (DivXLavcOpt->checkDivx3->isChecked())
                         withDivx3 = true;
                    else withDivx3 = false;

                    UpdateConversionCommandString();
               }
            break;

     case 6:
          if(!RawOptionsCheck){
               RawOpt = new RawOptDialog();  // only create if never done before
               RawOptionsCheck = true;
          }
          if (RawOpt->exec())
            {
              VideoOpts = RawOpt->getOptions();
              UpdateConversionCommandString();
            }
          break;
     default:
         break;
  }

}

void KonverterDialog::ShowAudioOptionsDialog()
{
  switch(OAFormatBox->currentItem()){
     case 0:
          if(!NoOptionsCheck){
               noOpt = new NoOptDialog();  // only create if never done before
               NoOptionsCheck = true;
          }
          noOpt->show();
          break;
     case 1:

          if(!MP3OptionsCheck){
               MP3Opt = new MP3OptDialog();
               MP3OptionsCheck = true;
          }
          if(MP3Opt->exec())
          {
                AudioOpts = MP3Opt->getOptions();
                UpdateConversionCommandString();
          }
          break;

     case 2:
          if(!PCMOptionsCheck){
               PCMOpt = new PCMOptDialog();
               PCMOptionsCheck = true;
          }
          if (PCMOpt->exec())
          {
               AudioOpts = "";
               UpdateConversionCommandString();
          }
          break;

     case 3:
          if(!MP2OptionsCheck){
               MP2Opt = new MP2OptDialog();
               MP2OptionsCheck = true;
          }
          if (MP2Opt->exec())
            {
              AudioOpts = MP2Opt->getOptions();
              UpdateConversionCommandString();
            }
          break;

     case 4:
          if(!AC3OptionsCheck){
               AC3Opt = new AC3OptDialog();
               AC3OptionsCheck = true;
          }
          if (AC3Opt->exec())
            {
              AudioOpts = AC3Opt->getOptions();
              UpdateConversionCommandString();
            }
          break;
     default:
         break;
  }
}

void KonverterDialog::ShowHelpDialog()
{
    helpPopUp = new KHelpMenu(this, KGlobal::instance()->aboutData(), false);

    buttonHelp->setAutoRepeat( FALSE );
    buttonHelp->setPopup(helpPopUp->menu());
}

void KonverterDialog::ShowAudioFilter()
{
   if (!(SoundFiltersCheck))
   {
      SFDialog = new SoundFilters(this);
      SoundFiltersCheck = true;
   }
   if (SFDialog->exec())
   {
      AudioFilt = SFDialog->getOptions();
      UpdateConversionCommandString();
   }
}

void KonverterDialog::ShowVideoFilter()
{
   if (!(VideoFiltersCheck))
   {
      VFDialog = new VideoFilters(this);
      VideoFiltersCheck = true;
   }
   if(VFDialog->exec())
   {
      VideoFilt= VFDialog->getOptions();
      UpdateConversionCommandString();
   }
}

void KonverterDialog::SplitNameChanged()
{
   SplitPartNameLabel->setText("Part name: "+SplitPrefLineEdit->text()+"1"+SplitSufLineEdit->text());
}

void KonverterDialog::getSplitter()
{
   SpFileExists = false;
   if ( InputNameBox->text() != "" && QFile::exists( InputNameBox->text() ) )
   {
   QFileInfo* SplitFileIndata = new QFileInfo(InputNameBox->text());
   SplitFileSize = SplitFileIndata->size();
   SplitmovieSizeLabel->setText("Movie size: "+ QString::number(SplitFileSize/1024/1024) + "Mb");
   SplitSlider->setMaxValue(SplitFileSize);
   SplitSlider->setValue(SplitFileSize/SplitPartsSpinBox->value());
   SplitSlider->setMinValue(SplitFileSize/98);
   SpFileExists = true;
      workDlg->TextOutput->clear();
   }
   else
   {
      workDlg->TextOutput->append( i18n("<h4><font color=red>Split: Input file does not exists!</font></h4>") );
   }
}

void KonverterDialog::SplitSliderChanged()
{
   if ( SpFileExists )
   {
      int Parts = 1;
      Parts = SplitFileSize / SplitSlider->value();
      SetParts(Parts);
   }
}

void KonverterDialog::SetParts(int Parts)
{
   if ( SpFileExists )
   {
      SplitPartsSpinBox->setValue(Parts);
      SplitPartsCountLabel->setText("Parts count: "+QString::number(Parts));
   }
}

void KonverterDialog::SplitSpinChanged()
{
   if ( SpFileExists )
   {
      SplitSlider->setValue(SplitFileSize/SplitPartsSpinBox->value());
      SplitPartSizeLabel->setText("Splitted part size: "+ QString::number((SplitFileSize/SplitPartsSpinBox->value())/1024/1024)+"Mb");
      SplitPartsCountLabel->setText("Parts count: "+SplitPartsSpinBox->text());
   }
}

void KonverterDialog::SplitMovie()
{
    if( running ){  // process is still running and user aborted
        running = false;
        SplitProcess->tryTerminate(); // trying the nice way...
        QTimer::singleShot( 3000, SplitProcess, SLOT( kill() ) );  // no reaction ? We'll try bazooka...
        workDlg->TextOutput->append( i18n("<h4><font color=red>Split: split aborted</font></h4>") );
    workDlg->doneworking("Split Aborted!");
     running = false;
     buttonConvert->setText("&Execute");
    }
    else
    {
     if ( SpFileExists && SplitPrefLineEdit->text() != "" && SplitSufLineEdit->text() != "")
     {
             SplitSpinChanged();
          SplitCurPart = 1;
          running = true;
          workDlg->ProgressBar->setProgress(0);
             SplitMovParts = SplitPartsSpinBox->value();
          SplitProcess = new KonvProcess();
           // connection the std output of mencoder to the textbox
          connect( SplitProcess, SIGNAL(readyReadStdout()),this, SLOT(SplitReadFromStdout()) );
          //connect( mencoder, SIGNAL(readyReadStderr()),this, SLOT(readFromStderr()) );  // disabled to supress bothering debug messages
          connect( SplitProcess, SIGNAL(processExited()),this, SLOT(SplitProcessExitting()) );
          SplitConstructCommand(1);

      workDlg->working(i18n("Splitting ")+mencoder->inFile());
          workDlg->show();

      SplitProcess->start();
          SplitCurPart++;
          buttonConvert->setText(i18n("Abort"));   // set abort button
     }
    }
}

void KonverterDialog::SplitProcessExitting()
{

     // check for part
     if( SplitCurPart <= SplitMovParts ){  // if divx
      workDlg->TextOutput->append("Constructing part "+ QString::number(SplitCurPart));

         // start the external mencoder
      SplitConstructCommand(SplitCurPart);
         if (!(SplitProcess->start())) {
           workDlg->TextOutput->append( i18n("<font color=red>Error! Something is wrong, maybe mencoder?</h3>"));
         }
      SplitCurPart++; // inc part
       }
      else
      {
        if ( running )
     {
             workDlg->ProgressBar->setProgress(100); // set to 100%
        running = false;
        SplitDoneMessage = new QMessageBox();
        buttonConvert->setText("&Execute");
        workDlg->doneworking("Splitting Done!");
         }
      else
      {
         running = false;
         buttonConvert->setText("&Execute");
         workDlg->ProgressBar->setProgress(0); // set to 0%
      }
     }
}

void KonverterDialog::SplitReadFromStdout()
{
    OutputLine = (QString)SplitProcess->readStdout();

      if(OutputLine.contains('%')) // if percent incremented since last step
      {
       if(LastStatus != OutputLine.mid(21,2)){  // if percentage changed
           workDlg->ProgressBar->setProgress(LastStatus.toInt());  // also increment progress bar
           LastStatus = OutputLine.mid(21,2);
       }
       if (SplitCurPart == 2)
       {
       if (SplitPosS != OutputLine.mid(4,4))
       {
          SplitPosS = OutputLine.mid(4,4);
//        textLog->append(posS);
       // debug: also print all console output
       //workDlg->TextOutput->append( OutputLine );
       SplitPosI = SplitPosS.toInt();
       }
       }
      }

}

void KonverterDialog::SplitConstructCommand(int part)
{
     QStringList tempList;
     tempList += "mencoder";
     tempList +=  "-ovc";
     tempList +=  "copy";
     tempList += "-oac";
     tempList += "copy";
     if (SplitCurPart == SplitPartsSpinBox->value())
     {
          tempList += "-ss";
          tempList += QString::number(SplitPosI*(part-1)-SplitSecsSpinBox->value());
     }
     else
     {
          if (part > 1)
          {
               tempList += "-ss";
               tempList += QString::number(SplitPosI*(part-1)-SplitSecsSpinBox->value());
          }
          SplitPosVal = SplitSlider->value()*part;
          tempList += "-endpos";
          if (part == 1)
          {
               tempList += QString::number(SplitPosVal)+"b";
          }
          else
               tempList += QString::number(SplitPosI);
     }
     SplitProcess->setMencOpts(tempList);
     SplitProcess->setOutFile( SplitPrefLineEdit->text() + QString::number(part) + SplitSufLineEdit->text());
     SplitProcess->setInFile ( InputNameBox->text() );

     //Debug
     workDlg->TextOutput->append(SplitProcess->getCommand());
}

QString KonverterDialog::ChShellEscape(QString escshell)
{
    escshell = escshell.replace(" ", "\\ ");
  return escshell;
}

void KonverterDialog::OpenPreview()
{
Pr = new Preview();
Pr->getFileKMPreview( mencoder->getOptions() , mencoder->inFile() );
Pr->showMaximized();
}

void KonverterDialog::ChangeMovInfo()
{
   movInfo->appendToQueue( mencoder->inFile() );
   movInfo->slotPlay();
   movInfo->slotStop();
   movInfoEdit->setText("");
   movInfoEdit->append( i18n("Video Codec: ")+movInfo->getVideoCodec() );
   if ( movInfo->getVideoBitrate() != 0 )
      movInfoEdit->append( i18n("Video Bitrate: ")+QString::number(movInfo->getVideoBitrate()) );
   else
      movInfoEdit->append( i18n("Video Bitrate: ")+i18n("unknown or variable") );
   movInfoEdit->append( i18n("Audio Codec: ")+movInfo->getAudioCodec() );
   movInfoEdit->append( i18n("Audio Bitrate: ")+QString::number(movInfo->getAudioBitrate()) );
   movInfoEdit->append( i18n("Movie Length: ")+movInfo->getLength().toString() );
   movInfoEdit->append( i18n("Size: ")+QString::number(movInfo->getVideoSize().width())+"x, "+QString::number(movInfo->getVideoSize().height())+"y");
}

void KonverterDialog::ExecWorkW()
{
      ExecuteCommandString();
}

void KonverterDialog::ExtraOptsCheck()
{
   switch(OVFormatBox->currentItem()){
   case 2:
      TwoPassCheckBox->setEnabled(true);
      break;
   case 5:
      TwoPassCheckBox->setEnabled(true);
      break;
   default:
      TwoPassCheckBox->setEnabled(false);
      TwoPassCheckBox->setChecked(false);
      break;
   }
}

void KonverterDialog::TwoPassChanged()
{
  if (TwoPassCheckBox->isChecked())
     mencPass=1;
  else
     mencPass=0;
}

void KonverterDialog::PrAoChanged()
{
   switch(PrAoDrBox->currentItem())
   {
   case 3:
      PrAoCheckBox->setEnabled(true);
      break;
   case 4:
      PrAoCheckBox->setEnabled(true);
      break;
   default:
      PrAoCheckBox->setEnabled(false);
      PrAoCheckBox->setChecked(false);
      break;
   }
   //needed to apply preferences without restart
   KConfig &config = *KGlobal::config();
   config.setGroup("Options");
   config.writeEntry("PrAoDriver",PrAoDrBox->currentText());
   config.writeEntry("PrAoBoth",PrAoCheckBox->isChecked());
   config.sync();
}

void KonverterDialog::InputFileChanged()
{
   TwoPassChanged(); //resets twopass mode (if file was changed)
   QFileInfo fi(InputNameBox->text());
   if(fi.exists())
   {
      PreviewButton->setEnabled(true);
      //ChangeMovInfo();
   }
   else
   {
      PreviewButton->setEnabled(false);
   }
}

bool KonverterDialog::checkConvert()
{
   //check if file exists
   QFileInfo fi(InputNameBox->text());
   if(!fi.exists()){
      KMessageBox::detailedSorry(this,i18n("Sorry, I can't find the file you specified."),i18n("The file ")+InputNameBox->text()+i18n(" does not exists."));
      return true;
   }

   //check if out directory is writable
   QFileInfo odi(mencoder->outDir());
   if (!odi.isWritable()){
      KMessageBox::detailedSorry(this,i18n("Sorry, No permissions to in this directory."),i18n("The directory ")+mencoder->outDir()+i18n(" is not writable."));
      return true;
      }
      else
      {
      QFileInfo ofi(mencoder->outFile());
      if(ofi.exists())
      if(KMessageBox::warningYesNo(this, i18n("The specified file already exists. Overwrite?"), i18n("File exists"),KStdGuiItem::yes(),KStdGuiItem::no(),i18n("Don't ask this queston again?")) != 3)
   return true;
   }

return false;
}
