/****************************************************************************
**
**
** Created: Sun April 11 22:06:51 2004
**      by: Varol Okan using the kate text editor
**
** This class is the main class for the QXine application.
**
** QXine is a small application fostering the xine libraries. It was neccesary
** to have a working interface to movie files for the 'Q' DVD-Author
** application and thus I created a small sub-project called QXine.
**
** From this information you should see why QXine is not a full featured
** video application. Sorry. Anyone interested in creating one though ?
**
****************************************************************************/
#include <unistd.h>

#include <qdatetimeedit.h>
#include <qapplication.h>
#include <qmessagebox.h>
#include <qtranslator.h>
#include <qpushbutton.h>
#include <qpushbutton.h>
#include <qfiledialog.h>
#include <qpopupmenu.h>
#include <qcombobox.h>
#include <qdatetime.h>
#include <qtoolbar.h>
#include <qslider.h>
#include <qaction.h>
#include <qlayout.h>
#include <qframe.h>
#include <qlabel.h>
#include <qimage.h>
#include <qdom.h>
#include <qdir.h>

#include "../utils.h"
#include "../CONFIG.h"
#include "qplayer_global.h"
#include "xml_qplayer.h"

#include "qplayer.h"
#include "mediacreator.h"
#include "dialogaboutqplayer.h"
#include "dialogconfigure.h"
#include "../filepreviewdialog.h"

#include "mediainfo.h"

QPlayer::QPlayer( QWidget* parent, const char* name, WFlags fl )
    : uiQPlayer ( parent, name, fl )
{
	MediaCreator::setPreferredEngine (QString ("DummyWidget"));
	m_iIsPlaying = STATE_STOPPED;
	m_iSubtitleTrack   = -1;
	m_iAudioTrack      = -1;
	m_bIgnoreSliderPos = false;
	// Next we will create the ComboBox in the MenuBar ...
	m_pMediaInterface  = NULL;
	m_pLanguagePopup   = NULL;
	m_pTranslator      = NULL;
	initLanguages();
	m_pToolBarPrevious  = new QToolBar (QString("Previous"), this, DockTop);
	m_pToolBarPrevious->setHorizontalStretchable ( true );
	m_pComboPrevious = new QComboBox (m_pToolBarPrevious);
	loadHistory ();
	// First we should create the XineWidget ...
	if (MediaCreator::preferredEngine () == QString ("DummyWidget"))	{
		if (QMessageBox::information (this, tr("Dummy set"), tr("The Media Backend is set to the DummyWidget,\nwhich does not have any functionality.\nDo you want to change the Media backend now ?"), QMessageBox::Yes, QMessageBox::No)	== QMessageBox::Yes)
			slotConfigure ();
	}
	m_pMediaInterface = MediaCreator::createPreferredWidget (m_pFramePreview, "MediaWidget");

	// Error !!! Lets pull the break on it ...
	m_pVideoLayout = new QGridLayout( m_pFramePreview, 1, 1, 4, 6, "XineMainLayout");
	m_pVideoLayout->addWidget (m_pMediaInterface->getWidget(), 0, 0);

	fileOpenAction->addTo      ( toolBar );
	fileOpenPrevious->addTo    ( toolBar );
	fileExitAction->addTo      ( toolBar );
	m_pActionScreenshot->addTo ( toolBar );
	m_pActionAbout->addTo      ( toolBar );

	m_pSliderTime->setRange (0, 65535);
	m_fSpeed = 1.0;
	
	m_pSliderVolume->setRange(0, 100);
	m_pSliderVolume->setValue(-80);

	m_pButtonPrev      ->setPaletteBackgroundColor (QColor (COLOR_QUICK_NORMAL));
	m_pButtonNext      ->setPaletteBackgroundColor (QColor (COLOR_QUICK_NORMAL));
	m_pButtonStop      ->setPaletteBackgroundColor (QColor (COLOR_QUICK_SELECTED));
	m_pButtonPlay      ->setPaletteBackgroundColor (QColor (COLOR_QUICK_NORMAL));
	m_pButtonSpeedPlus ->setPaletteBackgroundColor (QColor (COLOR_QUICK_NORMAL));
	m_pButtonSpeedMinus->setPaletteBackgroundColor (QColor (COLOR_QUICK_NORMAL));

	m_pButtonPrev      ->setPixmap (QPixmap().fromMimeSource( "prev_chapter.png" ));
	m_pButtonNext      ->setPixmap (QPixmap().fromMimeSource( "next_chapter.png" ));
	m_pButtonStop      ->setPixmap (QPixmap().fromMimeSource( "stop.png" ));
	m_pButtonPlay      ->setPixmap (QPixmap().fromMimeSource( "play.png" ));
	m_pButtonSpeedPlus ->setPixmap (QPixmap().fromMimeSource( "faster.png" ));
	m_pButtonSpeedMinus->setPixmap (QPixmap().fromMimeSource( "slower.png" ));

	editCopyAction  ->setIconSet( QIconSet( QPixmap::fromMimeSource( "editcopy" ) ) );
	fileExitAction  ->setIconSet( QIconSet( QPixmap::fromMimeSource( "exit.png" ) ) );
	fileOpenPrevious->setIconSet( QIconSet( QPixmap::fromMimeSource( "new.png" ) ) );
	fileOpenAction  ->setIconSet( QIconSet( QPixmap::fromMimeSource( "open.png" ) ) );
	fileSaveAction  ->setIconSet( QIconSet( QPixmap::fromMimeSource( "save.png" ) ) );
	editRedoAction  ->setIconSet( QIconSet( QPixmap::fromMimeSource( "redo" ) ) );
	editCutAction   ->setIconSet( QIconSet( QPixmap::fromMimeSource( "editcut" ) ) );
	editPasteAction ->setIconSet( QIconSet( QPixmap::fromMimeSource( "editpaste" ) ) );
	editFindAction  ->setIconSet( QIconSet( QPixmap::fromMimeSource( "searchfind" ) ) );
	m_pActionScreenshot->setIconSet( QIconSet( QPixmap::fromMimeSource( "desktop.png" ) ) );
	
	// The buttons fro the DVD menu guidance.
	connect ( m_pButtonUp,            SIGNAL ( clicked ( ) ), this, SLOT ( slotUp            ( ) ) );
	connect ( m_pButtonDown,          SIGNAL ( clicked ( ) ), this, SLOT ( slotDown          ( ) ) );
	connect ( m_pButtonLeft,          SIGNAL ( clicked ( ) ), this, SLOT ( slotLeft          ( ) ) );
	connect ( m_pButtonRight,         SIGNAL ( clicked ( ) ), this, SLOT ( slotRight         ( ) ) );
	connect ( m_pButtonSet,           SIGNAL ( clicked ( ) ), this, SLOT ( slotSet           ( ) ) );
	connect ( m_pButtonRoot,          SIGNAL ( clicked ( ) ), this, SLOT ( slotRoot          ( ) ) );
	connect ( m_pButtonTitle,         SIGNAL ( clicked ( ) ), this, SLOT ( slotTitle         ( ) ) );
	connect ( m_pButtonSubtitleMinus, SIGNAL ( clicked ( ) ), this, SLOT ( slotSubtitleMinus ( ) ) );
	connect ( m_pButtonSubtitlePlus,  SIGNAL ( clicked ( ) ), this, SLOT ( slotSubtitlePlus  ( ) ) );
	connect ( m_pButtonAudioMinus,    SIGNAL ( clicked ( ) ), this, SLOT ( slotAudioMinus    ( ) ) );
	connect ( m_pButtonAudioPlus,     SIGNAL ( clicked ( ) ), this, SLOT ( slotAudioPlus     ( ) ) );

	connect (m_pButtonPrev,       SIGNAL(clicked()), this, SLOT(slotPrev()));
	connect (m_pButtonNext,       SIGNAL(clicked()), this, SLOT(slotNext()));
	connect (m_pButtonStop,       SIGNAL(clicked()), this, SLOT(slotStop()));
	connect (m_pButtonPlay,       SIGNAL(clicked()), this, SLOT(slotPlay()));
	connect (m_pButtonSpeedPlus,  SIGNAL(clicked()), this, SLOT(slotSpeedPlus()));
	connect (m_pButtonSpeedMinus, SIGNAL(clicked()), this, SLOT(slotSpeedMinus()));
	connect (m_pSliderVolume,     SIGNAL(valueChanged(int)), this, SLOT(slotSetVolume(int)));
	connect (m_pSliderTime,       SIGNAL(sliderPressed ( ) ), this, SLOT(slotStartSeekPos ( ) ) );
	connect (m_pSliderTime,       SIGNAL(sliderReleased( ) ), this, SLOT(slotSeekPosition ( ) ) );
	
	connect (m_pComboPrevious,    SIGNAL(activated(int)), this, SLOT(slotHistory(int)));

	connect (m_pMediaInterface,   SIGNAL(signalPlaybackFinished ()), this, SLOT(slotPlaybackFinished()));
	connect (m_pMediaInterface,   SIGNAL(signalNewPosition(int, const QString&)), this, SLOT(slotNewPosition(int, const QString&)));
	connect (m_pActionSetup,      SIGNAL(activated()), this, SLOT(slotSetup()));
	connect (m_pActionConfigure,  SIGNAL(activated()), this, SLOT(slotConfigure()));
	connect (m_pActionMediaInfo,  SIGNAL(activated()), this, SLOT(slotMediaInfo()));
	connect (m_pActionScreenshot, SIGNAL(activated()), this, SLOT(slotScreenshot()));
}

QPlayer::~QPlayer()
{
	saveHistory();
}

void QPlayer::initLanguages()
{
	uint t;
	Utils theUtils;
	// Here we search the required directory for translation files and set the menu items 
	// under 'Tools->Languages'
//	QDir theFiles = QDir::home();
	QDir theFiles (PREFIX_DIRECTORY); // e.g. /usr/local
	theFiles.cd (PREFIX_DIRECTORY"/share/qdvdauthor");
	theFiles.setNameFilter ("qplayer_*.qm");
	QStringList listFiles = theFiles.entryList ();
	
	// Here we create the sub-menu for the additional languafges ...
	if (m_pLanguagePopup)
		delete m_pLanguagePopup;
	m_pLanguagePopup = new QPopupMenu ( this );
//	editMenu->insertItem( toolsLanguagesAction->iconSet(), tr( "Languages" ), m_pLanguagePopup );
	Tools->insertItem( tr( "Languages" ), m_pLanguagePopup );
	QAction *pActionLanguage = new QAction (this, "languageEnglish");
	pActionLanguage->setText( "English" );
	pActionLanguage->setMenuText( "English" );
	pActionLanguage->addTo( m_pLanguagePopup );

	for (t=0;t<listFiles.count();t++)	{
		// Frist we try to extract the language ...
		pActionLanguage = new QAction (this, QString ("language%1").arg(t));
		pActionLanguage->setText( theUtils.iso639(listFiles[t]) );
		pActionLanguage->setMenuText( theUtils.iso639(listFiles[t].mid (listFiles[t].length()-5,2)) );
		pActionLanguage->addTo( m_pLanguagePopup );
	}
	connect( m_pLanguagePopup, SIGNAL( activated(int) ), this, SLOT( slotChangeLanguage(int) ) );
}

void QPlayer::slotChangeLanguage (int iID)
{
	// The first thing is to co-relate the ID to the language ...
	QString qsID ("en");	// Default = english
	QDir theFiles (PREFIX_DIRECTORY); // e.g. /usr/local
	theFiles.cd (PREFIX_DIRECTORY"/share/qdvdauthor");
	theFiles.setNameFilter ("qplayer_*.qm");
	QStringList listFiles = theFiles.entryList ();
	// Now that we have the file list in the same order as they were generated, we can find the right one ...
	int iIndexOfID = m_pLanguagePopup->indexOf(iID);
	if (0 <= iIndexOfID-1)	// extract something like "de"
		qsID = listFiles[iIndexOfID-1].mid (listFiles[iIndexOfID-1].length()-5,2);

	// Here we install the language the user has chosen ...
	QTranslator *pTrans = new QTranslator( 0 );
	// Under /usr/share/qdvdauthor/
	QString qsLang = QString(QString (PREFIX_DIRECTORY"/share/qdvdauthor/qplayer_%1.qm").arg(qsID));
	if (m_pTranslator)	{
		qApp->removeTranslator ( m_pTranslator );
		delete m_pTranslator;
		m_pTranslator = NULL;	// Just for consistency ...
	}
	pTrans->load( qsLang );
	m_pTranslator = pTrans;
	qApp->installTranslator( m_pTranslator );
	languageChange();
}

void QPlayer::loadHistory ()
{
	int t;
	QFileInfo fileInfo;
	QString qsPlayerIniFile;
	qsPlayerIniFile = QDir::homeDirPath();
	qsPlayerIniFile.append(QPLAYER_INIT_DIR);

	// First we check for the existance of the settings directory ...
	QDir iniDir (qsPlayerIniFile);
	if (!iniDir.exists())
		iniDir.mkdir(qsPlayerIniFile);

	qsPlayerIniFile.append(QPLAYER_INIT_FILE);
	// Assign the file
	QFile iniFile(qsPlayerIniFile);
	if (!iniFile.open(IO_ReadOnly))
		return;
	// Try to get the right xml contents ...
	QDomDocument xmlDoc( XML_DOCTYPE_QPLAYER );
	if (!xmlDoc.setContent (&iniFile))	{
		// Error handling ...
		iniFile.close();
		QString qsOut = tr ( "QPlayer xml init file <%1> seems to be defective. Re-setting values.\n" ).arg ( qsPlayerIniFile );
		printf ( "%s", qsOut.ascii ( ) );
		return;
	}

	// First we clear the history ...
	m_listHistory.clear();
	m_pComboPrevious->clear();
	for (t=0;t<MAX_HISTORY_FILES;t++)
		m_listHistory.append (QString ());

	// Here is the main loop to extract the info ...
	QDomElement searchXMLTree;
	QDomElement docElem = xmlDoc.documentElement();
	QString  domText    = docElem.tagName();
	QDomNode xmlNode    = docElem.firstChild();
	QString qsVersion   = docElem.attributeNode(QPLAYER_VERSION).value();

	if (domText == QPLAYER_INI)	{
		// First we take care of the QDVDAuthor variables ...
		while( !xmlNode.isNull() ) {
			searchXMLTree = xmlNode.toElement();
			domText = searchXMLTree.text();
			if (QPLAYER_HISTORY  == searchXMLTree.tagName () )	{
				int iNumber = searchXMLTree.attributeNode(QPLAYER_NUMBER).value().toInt();
				m_listHistory[iNumber] = domText;
			}
			else if (QPLAYER_PREFERRED_ENGINE == searchXMLTree.tagName () )
				MediaCreator::setPreferredEngine (domText);
			else
				printf ("Warning: QPlayer::loadHistory -=> wrong XML Node <%s>\nContinuing ...\n",
						(const char *)searchXMLTree.tagName());
			// Go to the next node ...
			xmlNode = xmlNode.nextSibling();
		}
	}
	iniFile.close();
//printf ("QPlayer::laodHistory \n%s\n\n", (const char *)xmlDoc.toString());
	// Remove all empty entries ...
	m_listHistory.remove (QString ());
	// And finally we insert them into the combo box
	if (m_listHistory.count() > 0)	{
		for (t=m_listHistory.count()-1; t >= 0;t--)	{
			fileInfo.setFile (m_listHistory[t]);
			m_pComboPrevious->insertItem (fileInfo.fileName());
		}
		m_qsFileName = m_listHistory[m_listHistory.count()-1];
	}
}

void QPlayer::saveHistory ()
{
	uint t;
	QFileInfo fileInfo;
	QString qsPlayerIniFile;
	qsPlayerIniFile = QDir::homeDirPath();
	qsPlayerIniFile.append(QPLAYER_INIT_DIR);
	qsPlayerIniFile.append(QPLAYER_INIT_FILE);

	// First we create the document, ...
	QDomText domText;
	QDomElement elem, rootElem;
	QDomDocument xmlDoc( XML_DOCTYPE_QPLAYER );
	rootElem = xmlDoc.createElement  ( QPLAYER_INI );
	rootElem.setAttribute( QPLAYER_VERSION, "0.0.9" );

	elem = xmlDoc.createElement  ( QPLAYER_PREFERRED_ENGINE );
	domText = xmlDoc.createTextNode ( MediaCreator::preferredEngine() );
	elem.appendChild ( domText );
	rootElem.appendChild( elem );
	for (t=0;t<m_listHistory.count();t++)	{
		elem = xmlDoc.createElement  ( QPLAYER_HISTORY );
		domText = xmlDoc.createTextNode ( m_listHistory[t] );
		elem.appendChild ( domText );
		elem.setAttribute( QPLAYER_NUMBER, t );

		rootElem.appendChild( elem );
	}
	xmlDoc.appendChild( rootElem );

	// Assign the file
	QFile iniFile(qsPlayerIniFile);
	if (!iniFile.open(IO_WriteOnly))
		return;

	QString xml = xmlDoc.toString();
//printf ("QPlayer::saveHistory\n%s\n\n", (const char *)xml);

	iniFile.writeBlock(xml, qstrlen (xml));
	iniFile.close();
}

// The standard slots implemented in QXine ...
void QPlayer::fileOpen()
{
  QString qsFilter = "*.mpg *.vob *.avi *.m2v *.mpeg2";
  if ( m_pMediaInterface )  {
    MediaInfo *pInfo = m_pMediaInterface->getMediaInfo ( );
    if ( pInfo )
         qsFilter = pInfo->getExtensions ( true );
    else  {
      pInfo = MediaCreator::createInfo ( m_pMediaInterface->getMediaEngine ( ) );
      if ( pInfo )  {
           qsFilter = pInfo->getExtensions ( true );
           delete pInfo;
      }
    }
  }

  QString qsFileName = FilePreviewDialog::getOpenFileName ( m_pMediaInterface->getMediaEngine ( ),
                         QString::null, qsFilter, this );

  if ( qsFileName.isEmpty ( ) )
    return;
  setFileName ( qsFileName );

/*
	// Here we open the MovieDialog.
	// Note: THe preview depends on the same class as
	// the main VideoDiaplay in QXine, thus please
	// give some time to wrap up development ...
	QStringList listFileTypes;
	listFileTypes.append (tr ("Movie/Image Files (+Movies+ *.bmp *.png *.jpg *.gif *.xbm)"));
	listFileTypes.append (tr ("Movie Files (+Movies+)"));
	listFileTypes.append (tr ("Image Files (*.bmp *.png *.jpg *.gif *.xbm)"));
	listFileTypes.append (tr ("All Files (*)"));

	SourceFileDialog *pDialog = new SourceFileDialog (this);
	pDialog->setFileTypes (listFileTypes);
//	pDialog->initMe();
	int iReturn = pDialog->exec();
	if (iReturn == QDialog::Rejected)
		return;
	setFileName (pDialog->getFileName());
*/
}

void QPlayer::setFileName (QString qsFileName, bool bAddCurrentPath)
{
	m_qsFileName = qsFileName;
	if (bAddCurrentPath)
		addFileToHistory(QDir::currentDirPath() + QString ("/") + m_qsFileName);
	else
		addFileToHistory(m_qsFileName);
}

void QPlayer::setFileList (QValueList<QString> listVideos, bool bAddCurrentPath)
{
	uint t;
	for (t=0;t<listVideos.count (); t++)
		setFileName (listVideos[t], bAddCurrentPath);
}

void QPlayer::addFileToHistory(QString qsNewFile)
{
	if (qsNewFile.isEmpty())
		return;
	uint t;
	// This function will add the newly selected file name to the history combo box...

	// This line will remove any double names of the history
	m_listHistory.remove(qsNewFile);
	// The we check if we reached the max history number
	if (m_listHistory.count() >= MAX_HISTORY_FILES)	{
		QString qsFileToRemove = m_listHistory[0];
		m_listHistory.remove (qsFileToRemove);
	}
	// and finally we add the current file to the top of the pop ...
	m_listHistory.append(qsNewFile);
	m_pComboPrevious->clear();
	QFileInfo fileInfo;
	QString qsFileName;
	int iHistoryCount = m_listHistory.count()-1;
	for (t=0;t<m_listHistory.count();t++)	{
		qsFileName = m_listHistory[iHistoryCount - t];
		fileInfo.setFile(qsFileName);
		// Next we check if we are playing e.g. a DVD a la dvd:/path/VIDEO_TS/
		// in which case we extract dvd:/path
		if (fileInfo.fileName().isEmpty())	{
			int iPos = m_listHistory[iHistoryCount - t].find ("/VIDEO_TS/");
			if (iPos != -1)
				qsFileName = m_listHistory[iHistoryCount - t].left (iPos);
		}
//		m_pComboPrevious->insertItem(qsFileName);
		m_pComboPrevious->insertItem(fileInfo.fileName());
	}
	// Okay, we have now the information for the new Movie file to display.
	m_pLabelHeader->setText(QString("<p align=\"center\">%1</p>").arg(m_pComboPrevious->text(0)));
	// And finally we generate a first image ...
	getImage ();
}

void QPlayer::getImage(uint /* iFrameNumber */)
{
	// This should take care of the widget.
	m_pMediaInterface->openMRL(m_qsFileName);
	m_pMediaInterface->getScreenshot ();
}

void QPlayer::polish ()
{
	QWidget::polish ();
	
	if (m_pMediaInterface)	{
		m_pMediaInterface->initMediaEngine ();
		m_pMediaInterface->openMRL(QString ());
	}
}

void QPlayer::slotHistory(int iSelected)
{
	m_qsFileName = m_listHistory[m_listHistory.count() - iSelected - 1];
	addFileToHistory(m_qsFileName);
}

void QPlayer::slotUp ( )
{
  if ( m_pMediaInterface )
       m_pMediaInterface->setNavigate ( MediaInterface::NavigateUp );
}

void QPlayer::slotDown ( )
{
  if ( m_pMediaInterface )
       m_pMediaInterface->setNavigate ( MediaInterface::NavigateDown );
}

void QPlayer::slotLeft ( )
{
  if ( m_pMediaInterface )
       m_pMediaInterface->setNavigate ( MediaInterface::NavigateLeft );
}

void QPlayer::slotRight ( )
{
  if ( m_pMediaInterface )
       m_pMediaInterface->setNavigate ( MediaInterface::NavigateRight );
}

void QPlayer::slotSet ( )
{
  if ( m_pMediaInterface )
       m_pMediaInterface->setNavigate ( MediaInterface::NavigateSelect );
}

void QPlayer::slotRoot ( )
{
  if ( m_pMediaInterface )
       m_pMediaInterface->setMenu ( MediaInterface::MenuRoot );
}

void QPlayer::slotTitle ( )
{
  if ( m_pMediaInterface )
       m_pMediaInterface->setMenu ( MediaInterface::MenuTitle );
}

void QPlayer::slotSubtitleMinus ( )
{
  m_iSubtitleTrack --;
  if ( m_iSubtitleTrack < 0 )
    m_iSubtitleTrack = -1;
  if ( m_pMediaInterface )
       m_pMediaInterface->setSubtitleTrack ( m_iSubtitleTrack );
}

void QPlayer::slotSubtitlePlus ( )
{
  m_iSubtitleTrack ++;
  if ( m_iSubtitleTrack > 31 )
    m_iSubtitleTrack = 31;
  if ( m_pMediaInterface )
       m_pMediaInterface->setSubtitleTrack ( m_iSubtitleTrack );
}

void QPlayer::slotAudioMinus ( )
{
  m_iAudioTrack --;
  if ( m_iAudioTrack < 0 )
    m_iAudioTrack = -1;
  if ( m_pMediaInterface )
       m_pMediaInterface->setAudioTrack ( m_iAudioTrack );
}

void QPlayer::slotAudioPlus ( )
{
  m_iAudioTrack ++;
  if ( m_iAudioTrack > 7 )
    m_iAudioTrack = 7;
  if ( m_pMediaInterface )
       m_pMediaInterface->setAudioTrack ( m_iAudioTrack );
}

void QPlayer::slotPrev ()
{
	if (m_pMediaInterface->hasChapters())
		m_pMediaInterface->playChapter(-1);
	colorMovieButtons (m_pButtonPlay);
}

void QPlayer::slotNext ()
{
	if (m_pMediaInterface->hasChapters())
		m_pMediaInterface->playChapter(+1);
	colorMovieButtons (m_pButtonPlay);
}

void QPlayer::slotStop ()
{
	m_pMediaInterface->stop();
	colorMovieButtons (m_pButtonStop);
	m_pButtonPlay->setPixmap (QPixmap ().fromMimeSource("play.png"));
	m_iIsPlaying = STATE_STOPPED;
	m_pSliderTime->setValue ( 0 );
}

void QPlayer::slotPlay ()
{
	if (m_qsFileName.isEmpty())
		return;
//	if (m_pMediaWidget->isPlaying())	{
	if (m_iIsPlaying == STATE_PLAYING)	{
		m_iIsPlaying = STATE_PAUSED;
		m_pMediaInterface->pause();
		m_pButtonPlay->setPixmap (QPixmap ().fromMimeSource("play.png"));
	}
	else if (m_iIsPlaying == STATE_PAUSED)	{
		m_iIsPlaying = STATE_PLAYING;
		m_pMediaInterface->play();
		m_pButtonPlay->setPixmap (QPixmap ().fromMimeSource("pause.png"));
	}
	else 	{		
		QString qsFileName = m_qsFileName;
		m_pMediaInterface->playMRL(qsFileName);
		m_fSpeed = 1.0;
		colorMovieButtons (m_pButtonPlay);
		m_pButtonPlay->setPixmap (QPixmap ().fromMimeSource("pause.png"));
		m_iIsPlaying = STATE_PLAYING;
	}
}

void QPlayer::slotSpeedPlus ()
{
	if (m_fSpeed == 0.0)
		m_fSpeed = 0.25;
	else if (m_fSpeed == 0.25)
		m_fSpeed = 0.5;
	else if (m_fSpeed == 0.5)
		m_fSpeed = 1.0;
	else if (m_fSpeed == 1.0)
		m_fSpeed = 2.0;
	else  if (m_fSpeed == 2.0)
		m_fSpeed = 4.0;
	else	// default speed = normal playing speed
		m_fSpeed = 1.0;

	m_pMediaInterface->setSpeed(m_fSpeed);
//	m_pLabelSpeed->setText(QString("<p align=\"center\">%1</p>").arg(fSpeed));
	colorMovieButtons (m_pButtonSpeedPlus);
}

void QPlayer::slotSpeedMinus ()
{
	if (m_fSpeed == 4.0)
		m_fSpeed = 2.0;
	else if (m_fSpeed == 2.0)
		m_fSpeed = 1.0;
	else if (m_fSpeed == 1.0)
		m_fSpeed = 0.5;
	else if (m_fSpeed == 0.5)
		m_fSpeed = 0.25;
	else
		m_fSpeed = 0.0;

	m_pMediaInterface->setSpeed(m_fSpeed);
//	m_pLabelSpeed->setText(QString("<p align=\"center\">%1</p>").arg(fSpeed));
	colorMovieButtons (m_pButtonSpeedMinus);
}

void QPlayer::slotPlaybackFinished ()
{
	colorMovieButtons (m_pButtonStop);
	m_pButtonPlay->setPixmap (QPixmap ().fromMimeSource("play.png"));
	m_pSliderTime->setValue ( 0 );
	m_iIsPlaying = STATE_STOPPED;
}

void QPlayer::colorMovieButtons (void *pButton)
{
	static QPushButton *pPreviousButton = m_pButtonStop;
	pPreviousButton->setPaletteBackgroundColor (QColor (COLOR_QUICK_NORMAL));
	pPreviousButton = (QPushButton *)pButton;
	pPreviousButton->setPaletteBackgroundColor (QColor (COLOR_QUICK_SELECTED));
}

void QPlayer::slotNewPosition (int iPos, const QString& qsTime)
{
  // iPos [0 .. 65535]
  //printf (" QPlayer::slotNewPosition <%d><%s> Ignore<%d>\n", iPos, (const char *)qsTime, m_bIgnoreSliderPos );
  if ( ! m_bIgnoreSliderPos )
    m_pSliderTime->setValue ( iPos );
  m_pLabelTime->setText (QString("<p align=\"center\">%1</p>").arg(qsTime));
}


void QPlayer::slotSetup ()
{
	m_pMediaInterface->setupDialog ();
}

void QPlayer::slotConfigure ()
{
	// Note since MediaCreator is static we don't need to pass infos here :)
	ConfigureDialog *pDialog = new ConfigureDialog ();
	pDialog->m_pMediaInterface = m_pMediaInterface;
	pDialog->exec();
}

void QPlayer::slotMediaInfo ()
{
	MediaInfo *pMediaInfo = MediaCreator::createInfo(m_pMediaInterface->getMediaEngine());
	pMediaInfo->setFileName (m_qsFileName);
//	pMediaInfo->test_print ();
	QString qsInfo;
	qsInfo += QString ("FileName   : %1\n").arg(pMediaInfo->getFileName ());
	qsInfo += QString ("Has Video  : %1\n").arg(pMediaInfo->hasVideo () ? QString("true") : QString("false"));
	qsInfo += QString ("Has Audio  : %1\n\n").arg(pMediaInfo->hasAudio () ? QString("true") : QString("false"));

	qsInfo += QString ("Length     : %1 (%2 ticks)\n").arg(pMediaInfo->getLengthString ()).arg(pMediaInfo->getLength ());
	qsInfo += QString ("Ratio      : %1\n").arg(pMediaInfo->getRatio ());
	qsInfo += QString ("Format     : Video<%1> Audio<%2>\n").arg(pMediaInfo->getFormat(true)).arg(pMediaInfo->getFormat (false));
	qsInfo += QString ("Codec      : Video<%1> Audio<%2>\n").arg(pMediaInfo->getCodec (true)).arg(pMediaInfo->getCodec (false));
	qsInfo += QString ("Size       : %1\n").arg(pMediaInfo->getSizeString ());
	qsInfo += QString ("Resolution : %1\n").arg(pMediaInfo->getResolutionString ());
	qsInfo += QString ("FPS        : %1\n").arg(pMediaInfo->getFPS ());
	qsInfo += QString ("Sample     : %1 <%2>\n").arg(pMediaInfo->getSample ()).arg(pMediaInfo->getSampleString ());
	qsInfo += QString ("BPS (Video): %1 <%2>\n").arg(pMediaInfo->getBPS (true)).arg(pMediaInfo->getBPSString (true));
	qsInfo += QString ("BPS (Audio): %1 <%2>\n").arg(pMediaInfo->getBPS (false)).arg(pMediaInfo->getBPSString (false));
	qsInfo += QString ("Bits       : %1\n\n").arg(pMediaInfo->getBits ());

	qsInfo += QString ( "Status     : %1\n").arg(pMediaInfo->getStatus ());

	QMessageBox::information (NULL, tr ("Media information"), qsInfo, QMessageBox::Ok);

	delete pMediaInfo;
}
/*
	QString getFileName (bool b=true);
	unsigned long int getLength ();
	QString getLengthString ();
	QString getRatio        ();
	QString getFormat       (bool);
	QString getCodec        (bool);
	uint    getSize         ();
	QString getSizeString   ();
	int     getResolution   (bool);
	QString getResolutionString ();
	float   getFPS          ();
	QString getStatus       ();
	int     getSample       ();
	QString getSampleString ();
	int     getBPS          (bool);
	QString getBPSString    (bool);
	int     getBits         ();

	bool hasAudio ();
	bool hasVideo ();
*/
void QPlayer::slotSetVolume (int iVolume)
{
  float fValue = (float)(100 - iVolume) / 100.0;
  //  printf ( "QPlayer::slotSetVolume <%f>\n", fValue );
  if ( m_pMediaInterface )
       m_pMediaInterface->setVolume ( fValue );
}

void QPlayer::slotStartSeekPos ()
{
  m_bIgnoreSliderPos = true;
}

void QPlayer::slotSeekPosition ()
{
  int iPosition = m_pSliderTime->value ( );
  //printf ( "QPlayer::slotSeekPosition <%d>\n", iPosition );
  if ( m_pMediaInterface )
       m_pMediaInterface->setPosition ( iPosition );
  m_bIgnoreSliderPos = false;
}

void QPlayer::fileOpenRecent()
{
}

void QPlayer::fileExit()
{
	close();
}

void QPlayer::slotScreenshot()
{
	Utils theUtils;
	long iMsecOffset  = 0;
	QString qsCurrent = m_pLabelTime->text (); //QString("<p align=\"center\">%1</p>").arg(qsTime));
printf ( "<%s> ", qsCurrent.ascii () );
	qsCurrent.remove ( "<p align=\"center\">" );
	qsCurrent.remove ( "</p>" );
	iMsecOffset = theUtils.getMsFromString ( qsCurrent );
printf ( "%ld %s\n", iMsecOffset, qsCurrent.ascii() );
//	MediaInfo *pMediaInfo = m_pMediaInterface->getMediaInfo ( );

	QImage screenShot;
//	if ( pMediaInfo )
//		screenShot = pMediaInfo->getScreenshot ( iMsecOffset );
//	else
		screenShot = m_pMediaInterface->getScreenshot ( (float)(iMsecOffset / 1000.0f) );
	
	if (screenShot.isNull()) {
	  printf ( "Could not create screenshot\n" );
	  return;
	}
	
	QString qsFileName = QFileDialog::getSaveFileName("./", tr("Images (*.png *.xpm *.jpg)"), this, tr("save file Dialog"), tr("Save Screenshot under ..."));

	if (qsFileName.isEmpty())
		return;
	QFileInfo fileInfo (qsFileName);
	QString qsExtension = fileInfo.extension();
	qsExtension = qsExtension.upper();
	screenShot.save (qsFileName, qsExtension);
}

void QPlayer::helpAbout()
{
	AboutQPlayer *pDialog = new AboutQPlayer (this);
	pDialog->m_pLabelTux->setPixmap (QPixmap().fromMimeSource ("babytux.png"));
	pDialog->show();
}


/*
void QPlayer::slotScreenshot()
{
	uchar *pRgbPile = NULL;
	int iWidth, iHeight;
	double fScaleFactor;

	m_pMediaWidget->GetScreenshot (pRgbPile, iWidth, iHeight, fScaleFactor);
	
	if (!pRgbPile)
		return;
	QImage screenShot(pRgbPile, iWidth, iHeight, 32, 0, 0, QImage::IgnoreEndian);
	if (fScaleFactor >= 1.0)
		iWidth = (int)((double) iWidth * fScaleFactor);
	else
		iHeight = (int) ((double) iHeight / fScaleFactor);

	screenShot = screenShot.smoothScale(iWidth, iHeight);
	
	QString qsFileName = QFileDialog::getSaveFileName("./", tr("Images (*.png *.xpm *.jpg)"), this, tr("save file Dialog"), tr("Save Screenshot under ..."));

	if (qsFileName.isEmpty())
		return;
	QFileInfo fileInfo (qsFileName);
	QString qsExtension = fileInfo.extension();
	qsExtension = qsExtension.upper();
	screenShot.save (qsFileName, qsExtension);

	delete []pRgbPile;	
}

void QPlayer::loadHistory ()
{
#ifdef QXINE
	// This function uses the xine-lib functionality, to restore the last iNrOfHistory
	// loaded files.
	xine_cfg_entry_t config;
	config.str_value = 0;
	xine_t *pXineEngine = (xine_t *)m_pMediaWidget->GetXineEngine();
	uint t;
	char cBuffer[100];
	QFileInfo fileInfo;
	// First we clear the history ...
	m_listHistory.clear();
	m_pComboPrevious->clear();

	// Done in InitXine ...
//	QString qsConfigFile = QDir::homeDirPath();
//	qsConfigFile.append("/.qdvdauthor/qxine_config");
//	if (QFile::exists(configFile))
//		xine_config_load (xineEngine, configFile);
	// And here we get the last five history files ...
	for (t=0;t<MAX_HISTORY_FILES;t++)	{
		sprintf (cBuffer, "gui.history%d", t+1);
		xine_config_register_string (pXineEngine, cBuffer, "", "History File", "This value holds one History file", 0 , NULL, NULL);
		xine_config_lookup_entry (pXineEngine, cBuffer, &config);
		if (QString(config.str_value).isEmpty())
			continue;
		fileInfo.setFile (config.str_value);
		m_listHistory.append (config.str_value);
		m_pComboPrevious->insertItem(fileInfo.fileName());
	}
#endif
}

void QPlayer::saveHistory ()
{
#ifdef QXINE
	uint t;
	char cKey[50];
	xine_cfg_entry_t config;
	xine_t *pXineEngine = (xine_t *)m_pMediaWidget->GetXineEngine();

    xine_config_lookup_entry (pXineEngine, "gui.history1", &config);
	config.help = "This value holds one History file";
	config.type = XINE_CONFIG_TYPE_STRING;
	for (t=0;t<m_listHistory.count();t++)	{
		sprintf (cKey, "gui.history%d", t+1);
		xine_config_register_string (pXineEngine, cKey, "", "History File", "This value holds one History file", 0 , NULL, NULL);
//printf ("<%s>=<%s>\n", cKey, (const char *)m_listHistory[t]);
		config.key = cKey;
		config.str_value = (char *)(const char *)m_listHistory[t];
		xine_config_update_entry (pXineEngine, &config);
	}
	QString qsConfigFile = QDir::homeDirPath();
	qsConfigFile.append("/.qdvdauthor/qxine_config");
	xine_config_save (pXineEngine, (const char *)qsConfigFile);
#endif
}
*/

