/****************************************************************************
** Form implementation generated from reading ui file 'uidialogsetup.ui'
**
** Created: Wed Sep 09 07:53:05 2004
**
** Here we handle the DialogSetup, which is called from 
** Tools->Setup
**
** This dialog also handles the scaning of the system for all neccesary tools
** -> The neccesary tools are defined in globalk.h
****************************************************************************/
#include <stdlib.h>
#include <unistd.h>

#include <qdatetimeedit.h>
#include <qradiobutton.h>
#include <qcolordialog.h>
#include <qscrollview.h>
#include <qfiledialog.h>
#include <qfontdialog.h>
#include <qpushbutton.h>
#include <qlineedit.h>
#include <qcheckbox.h>
#include <qgroupbox.h>
#include <qcombobox.h>
#include <qspinbox.h>
#include <qlayout.h>
#include <qcursor.h>
#include <qlabel.h>
#include <qframe.h>
#include <qfont.h>

#include "global.h"
#include "utils.h"
#include "qdvdauthorinit.h"
#include "dialogman.h"
#include "dialogsetup.h"
#include "messagebox.h"
#include "dialogtemp.h"
#include "qplayer/mediacreator.h"

#define COLOR_ME_RED    255,  50,  50
#define COLOR_ME_ORANGE 255, 150,  50
#define COLOR_ME_WHITE  255, 250, 250

// Here are the true DialogSetup functions ...
DialogSetup::DialogSetup(QWidget *pParent, const char *pName, WFlags flags)
    : uiDialogSetup (pParent, pName, flags)
{
	m_bModifiedToolsPaths = false;
	m_pScrollFrame        = NULL;
	m_pScrollView         = NULL;
	m_pDNDContainer       = NULL;
	m_iMaxHistoryFiles    = 10;
	m_qsStyle             = QString ("Default");

	uint t = 0;
	QStringList listEngines = MediaCreator::getAvailableEngines ();
	for (t=0;t<listEngines.count();t++)
		comboPreferredEngine->insertItem (listEngines[t]);
	comboPreferredEngine->setCurrentText (MediaCreator::preferredEngine());
	m_pTimeEditDuration->setTime ( QTime ( 0, 0, 1 ) );

	initExternalPlayerList ();
	m_pSpinMaxThreads->setValue (Global::iMaxRunningThreads);
	m_pCheckDeleteOlder->setChecked (true);
	m_pEditOlderThan->setText (QString ("%1").arg(Global::iDeleteTempOlderThan));
	if (Global::iDeleteTempOlderThan < 0)	{
		m_pCheckDeleteOlder->setChecked (false);
		m_pEditOlderThan->setText (QString ("%1").arg(-Global::iDeleteTempOlderThan));
		m_pEditOlderThan->setEnabled (false);
	}

	connect (m_pButtonAdminTemp  , SIGNAL (clicked()), this, SLOT(slotAdminTemp()));
	connect (m_pButtonScan       , SIGNAL (clicked()), this, SLOT(slotScanSystem()));
	connect (m_pButtonBrowseProjectPath, SIGNAL (clicked()), this, SLOT(slotBrowseProjectPath()));
	connect (tabWidget, SIGNAL (currentChanged (QWidget*)), this, SLOT(slotTabChanged(QWidget *)));
	connect (comboPreferredEngine, SIGNAL (activated(const QString &)), this, SLOT (slotPreferredEngineChanged(const QString &)));
	
	connect (m_pSpinAutosave     , SIGNAL (valueChanged(int)), this, SLOT(slotAutosaveChanged(int)));
	connect (m_pSpinMaxHistory   , SIGNAL (valueChanged(int)), this, SLOT(slotMaxHistoryChanged(int)));
	connect (m_pButtonReset      , SIGNAL (clicked()), this, SLOT(slotResetHistory()));
	connect (m_pButtonBrowseTemp , SIGNAL (clicked()), this, SLOT(slotBrowseTemp()));
	connect (m_pButtonSetupEngine, SIGNAL (clicked()), this, SLOT(slotSetupEngine()));
	connect (m_pButtonEngineInfo , SIGNAL (clicked()), this, SLOT(slotEngineInfo()));
	connect (m_pButtonFont       , SIGNAL (clicked()), this, SLOT(slotFont ()));
	connect (m_pButtonColor      , SIGNAL (clicked()), this, SLOT(slotColor()));
	
	// Drag'n Drop tab-paged
	connect (m_pRadioImageButton, SIGNAL (stateChanged(int)), this, SLOT (slotImageButton(int)));
	connect (m_pRadioMovieButton, SIGNAL (stateChanged(int)), this, SLOT (slotMovieButton(int)));
	connect (m_pCheckWithText   , SIGNAL (toggled(bool))    , this, SLOT (slotWithText   (bool)));
	connect (m_pCheckDeleteOlder, SIGNAL (toggled(bool))    , this, SLOT (slotDeleteOlder(bool)));
}

DialogSetup::~DialogSetup()
{
	uint t;
	for (t=0;t<m_listToolsPaths.count();t++)
		delete m_listToolsPaths[t];
	m_listToolsPaths.clear ();
}

void DialogSetup::slotAdminTemp ()
{
	DialogTemp *pDialog = new DialogTemp (this);

	pDialog->exec();
	delete pDialog;
}

void DialogSetup::initExternalPlayerList ()
{
	// Okay, now we should try to look fort the following players ...
	uint t;
	char *arrayPlayers[14] = {"qplayer", "xine", "mplayer", "kaffeine", "kmplayer", "kplayer", "vlc", "ogle", "helix", "totem", "sinek", "okle", "xfmedia", "gtkplayer"};
	Utils theUtils;
	QString qsPlayer;
	for (t=0;t<14;t++)	{
		qsPlayer = theUtils.checkForExe (arrayPlayers[t]);
		if (!qsPlayer.isEmpty())
			m_pComboExternalPlayer->insertItem (qsPlayer);
	}
	m_pComboExternalPlayer->setCurrentText (Global::qsExternalPlayer);
}   
/*
void DialogSetup::initExternalPlayerList ()
{
	// Okay, now we should try to look fort the following players ...
	uint t;
	char *arrayPlayers[14] = {"qplayer", "xine", "mplayer", "kaffeine", "kmplayer", "kplayer", "vlc", "ogle", "helix", "totem", "sinek", "okle", "xfmedia", "gtkplayer"};
QFileInfo fileInfo(QString("%1/%2_out.txt").arg(Global::qsTempPath).arg(getlogin()));
	for (t=0;t<3;t++)	{
		// the next check is to see if we can find kdesu
	system ((const char *)QString ("which %1 > %2/%3_out.txt 2>/dev/null").arg(arrayPlayers[t]).arg(Global::qsTempPath).arg(getlogin()));
		fileInfo.setFile(QString("%1/%2_out.txt").arg(Global::qsTempPath).arg(getlogin ()));
		// Okay we can not find it, so we wont bother asking the user ...
		if (fileInfo.size() > 4)	{
			m_pComboExternalPlayer->insertItem (arrayPlayers[t]);
		}
	}
	m_pComboExternalPlayer->setCurrentText (Global::qsExternalPlayer);
}   
*/
void DialogSetup::slotPreferredEngineChanged(const QString &qsNewText)
{
	MediaCreator::setPreferredEngine (qsNewText);
}

bool DialogSetup::modifiedToolsPaths()
{
	// This returns a flag telling if the user changed all or some of the tools paths ...
	return m_bModifiedToolsPaths;
}

void DialogSetup::slotBrowseProjectPath()
{
	// This function will browse for the directory where the DVD is to be build.
	QString qsPathName = QFileDialog::getExistingDirectory ( m_pEditProjectPath->text() );
	if  ( (qsPathName.isEmpty()) || (qsPathName.isNull()) )
		return;
	m_pEditProjectPath->setText(qsPathName);
}

void DialogSetup::setToolsPaths(QValueList<Utils::toolsPaths *> &listToolsPaths)
{
	uint t, i, iIndex;
	bool bFoundLostTool;
	QValueList<uint> listOfTheLostTools;
	QValueList<QString> listOfTheFoundTools;
	Utils theUtils;
	// Here we create the ScrollView ... Note this is the only function which creates these widgets.
	QFrame *pTempFrame = m_pScrollFrame;
	// The first check is to see if the list has any values ...
	QCursor myCursor (QCursor::WaitCursor);
	setCursor (myCursor);
	if (listToolsPaths.count() == 0)
		return slotScanSystem();	// If not, then slotScanSystem will call this function here.

	// If the scrollview does exist then we can delete it now and re-create it.
	// Note: This will also delete all objects inside the ScrollView.
	if (!m_pScrollView)	{
		m_pScrollView = new QScrollView (Widget3, "SetupScrollView");
		m_pScrollLayout->addWidget ( m_pScrollView );
		m_pScrollView->setVScrollBarMode ( QScrollView::AlwaysOn );
	}
	// And this Frame will hold all neccesarywidgets ...
	m_pScrollFrame = new QFrame( m_pScrollView->viewport (), "m_pScrollFrame" );
	m_pScrollFrame->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)1, (QSizePolicy::SizeType)1, 0, 0, m_pScrollFrame->sizePolicy().hasHeightForWidth() ) );
	m_pScrollFrame->setPaletteBackgroundColor( QColor( 177, 211, 238 ) );
	m_pScrollFrame->setFrameShape( QFrame::GroupBoxPanel );
	m_pScrollFrame->setFrameShadow( QFrame::Sunken );
	m_pScrollFrame->setMinimumWidth ( m_pLabelHeader->width() - 20 );
	
	QHBoxLayout *pHLayoutMain = new QHBoxLayout ( m_pScrollFrame ); // 0, 0, 6, "HLayout" );
	QVBoxLayout *pVLayout1 = new QVBoxLayout ( NULL, 4, 6, "VLayout1" );
	QVBoxLayout *pVLayout2 = new QVBoxLayout ( NULL, 4, 6, "VLayout2" );

	m_listButtons.clear();
	m_listManButtons.clear();
	// Now we build in some complexity ...
	// In order to have all tools top first which were NOT found, we have a dry - run first in which we create the list 
	// of order to display the tools plus found / not-found flags for background coloring.
	// Also we create a global translation list to get from the original order to the new order.
	m_listIndex.clear ();
	for (t=0;t<listToolsPaths.count();t++)	{
		if ( !listToolsPaths[t]->bPresent )	{
			listOfTheLostTools.append (t);
			listOfTheFoundTools.append ( listToolsPaths[t]->qsExecutableName);
		}
		else
			listOfTheFoundTools.append ( listToolsPaths[t]->qsFullPath );
	}
	// Now we create the index-list. First all tools not found ...
	m_listIndex = listOfTheLostTools;
	for (t=0;t<listToolsPaths.count();t++)	{
		bFoundLostTool = false;
		// Here we add the remainder ...
		for (i=0;i<listOfTheLostTools.count();i++)	{
			if (t == listOfTheLostTools[i])	{
				bFoundLostTool = true;
				// And here we exit this inner loops since we found what we were looking for.
				i = listOfTheLostTools.count();
			}
		}
		if (!bFoundLostTool)
			m_listIndex.append(t);
	}
	
	m_listEditToolsPaths.clear();
	m_listTools.clear();
	// At this point I have the information I need to create the GUI elements.
	for (t=0;t<listToolsPaths.count();t++)	{
		iIndex = m_listIndex[t];
		QLabel *pToolLabel = new QLabel( m_pScrollFrame, QString("pToolLabel%1").arg(iIndex) );
		pVLayout1->addWidget( pToolLabel );
		pToolLabel->setText (theUtils.getToolsDisplayName(listToolsPaths[iIndex]->qsExecutableName));

		QHBoxLayout *pHLayout = new QHBoxLayout(  );

		QLineEdit *pEditToolsPath = new QLineEdit( m_pScrollFrame, QString("pEditToolsPath%1").arg(iIndex) );
		m_listEditToolsPaths.append (pEditToolsPath);
		pHLayout->addWidget( pEditToolsPath );
		if (t<listOfTheLostTools.count())	{
			if (theUtils.isMandatory(iIndex))
				pEditToolsPath->setBackgroundColor(QColor (COLOR_ME_RED));
			else
				pEditToolsPath->setBackgroundColor(QColor (COLOR_ME_ORANGE));
		}
//		pEditToolsPath->setText( toolsArray[iIndex].pExecutableName );
		pEditToolsPath->setText( listOfTheFoundTools[iIndex] );
		connect (pEditToolsPath, SIGNAL(textChanged(const QString &)), this, SLOT(slotModifiedToolsPath(const QString &)));
		m_listTools.append ( listToolsPaths[iIndex]->qsExecutableName );

		QPushButton *pButtonInfo = new QPushButton( m_pScrollFrame, QString("m_pButtonBrowseProjectPath%1").arg(iIndex) );
		pButtonInfo->setText (tr("Info"));
		connect (pButtonInfo, SIGNAL(clicked()), this, SLOT(slotButtonInfo()));
		// Now we add teh button to the buttonList. This is needed to later on 
		// decide which button has been pressed (QObject::sender() does return the Object pointer)
		m_listButtons.append (pButtonInfo);

		
		QPushButton *pButtonMan = new QPushButton( m_pScrollFrame, QString("m_pButtonBrowseProjectPath%1").arg(iIndex) );
		if (t<listOfTheLostTools.count())
			pButtonMan->setText (tr("Search ..."));
		else 
			pButtonMan->setText (tr("man"));
		connect (pButtonMan, SIGNAL(clicked()), this, SLOT(slotButtonMan()));
		// Now we add teh button to the buttonList. This is needed to later on 
		// decide which button has been pressed (QObject::sender() does return the Object pointer)
		m_listManButtons.append (pButtonMan);

		pHLayout->addWidget(  pButtonMan );
		pHLayout->addWidget( pButtonInfo );
		// Finally we add our creation to the main layout
		pVLayout2->addLayout( pHLayout );
	}
	pHLayoutMain->addLayout ( pVLayout1 );
	pHLayoutMain->addLayout ( pVLayout2 );

	// Okay we waited until after scanning the system to deleet the previous frame (f any)
	if (pTempFrame)	{
		m_pScrollView->removeChild (pTempFrame);
		delete pTempFrame;
	}
	// And now let us happily activate the new Frame ...
	m_pScrollView->addChild ( m_pScrollFrame );
	m_pScrollView->show();
	m_pScrollFrame->show();
	myCursor = QCursor(QCursor::ArrowCursor);
	
	// Here we create the objects for m_listToolsPaths of type <Utils::toolsPaths *>
	for (t=0;t<m_listToolsPaths.count();t++)
		delete m_listToolsPaths[t];
	m_listToolsPaths.clear ();
	m_listToolsPaths = getToolsPathsList();

	setCursor (myCursor);
}

void DialogSetup::setDragNDrop (DragNDropContainer *pDNDContainer)
{
	m_pDNDContainer = pDNDContainer;
	m_pEditThumbnailWidth      ->setText(QString("%1").arg(pDNDContainer->sizeThumbnail.width()));
	m_pEditThumbnailHeight     ->setText(QString("%1").arg(pDNDContainer->sizeThumbnail.height()));
	m_pEditButtonWidth         ->setText(QString("%1").arg(pDNDContainer->sizeButton.width()));
	m_pEditButtonHeight        ->setText(QString("%1").arg(pDNDContainer->sizeButton.height()));
	m_pRadioImageButton        ->setChecked( pDNDContainer->bImageButton);
	m_pRadioMovieButton        ->setChecked(!pDNDContainer->bImageButton);
	m_pCheckStartAfterDropEvent->setChecked( pDNDContainer->bStartAfterDropEvent);
	m_pCheckWithText           ->setChecked( pDNDContainer->bWithText);
	m_pComboTextPosition       ->setCurrentItem( pDNDContainer->iTextPosition-1);	// Note that the enum type starts with TEXT_POS_UNDEF
	m_pTimeEditStartOffset ->setTime  (pDNDContainer->timeStartOffset);
	m_pTimeEditDuration    ->setTime  (pDNDContainer->timeDuration);
	m_pSpinPriority        ->setValue (pDNDContainer->iHowNiceShouldIBe);

	m_pGroupBox4->setEnabled (!pDNDContainer->bImageButton);
	m_pTimeEditStartOffset->setEnabled(!pDNDContainer->bImageButton);
	m_pTimeEditDuration   ->setEnabled(!pDNDContainer->bImageButton);
	m_font                = m_pDNDContainer->font;
	m_colorForeground     = pDNDContainer->colorForeground;
}

void DialogSetup::setHistory (int iMaxHistoryFiles, QStringList listHistory, QValueList<QPixmap *>listHistoryPix)
{
	m_listHistory      = listHistory;
	m_listHistoryPix   = listHistoryPix;
	m_iMaxHistoryFiles = iMaxHistoryFiles;
	m_pSpinMaxHistory->setValue (iMaxHistoryFiles);
}

void DialogSetup::setAutosave (int iAutosave)
{
	m_iAutosave = iAutosave;
	m_pSpinAutosave->setValue (iAutosave);
}

void DialogSetup::setStyle (QString qsStyle)
{
	m_qsStyle = qsStyle;
}

int DialogSetup::getAutosave ()
{
	return m_iAutosave;
}

bool DialogSetup::resetHistory()
{
	if (m_listHistory.count() == 0)
		return true;
	return false;
}

int DialogSetup::maxHistoryFiles ()
{
	return m_iMaxHistoryFiles;
}

void DialogSetup::accept ()
{
	if (m_pDNDContainer)	{
		// Here we set the values for the Drag'n Drop, so we can later on store them in the init - file.
		if ( (m_pEditThumbnailWidth->text().toInt() > 0) && (m_pEditThumbnailHeight->text().toInt() > 0) )
			m_pDNDContainer->sizeThumbnail = QSize (m_pEditThumbnailWidth->text().toInt(), m_pEditThumbnailHeight->text().toInt());
		if ( (m_pEditButtonWidth->text().toInt() > 0) && (m_pEditButtonHeight->text().toInt() > 0) )
			m_pDNDContainer->sizeButton = QSize (m_pEditButtonWidth->text().toInt(), m_pEditButtonHeight->text().toInt());

		m_pDNDContainer->bImageButton         = m_pRadioImageButton   ->isChecked();
		m_pDNDContainer->bWithText            = m_pCheckWithText      ->isChecked();
		m_pDNDContainer->iTextPosition        = m_pComboTextPosition  ->currentItem()+1;// Note that the enum type starts with TEXT_POS_UNDEF
		m_pDNDContainer->iHowNiceShouldIBe    = m_pSpinPriority->value();
		m_pDNDContainer->font                 = m_font;
		m_pDNDContainer->colorForeground      = m_colorForeground;
		m_pDNDContainer->timeStartOffset      = m_pTimeEditStartOffset->time();
		m_pDNDContainer->timeDuration         = m_pTimeEditDuration   ->time();
		m_pDNDContainer->bStartAfterDropEvent = m_pCheckStartAfterDropEvent->isChecked();
	}
	// And then we store the ini - file ...
	QDVDAuthorInit *pInit = new QDVDAuthorInit (m_listToolsPaths, m_pDNDContainer);
	// init of those vars after readInitFile (in constructor)
	Global::iMaxRunningThreads   = m_pSpinMaxThreads->value ();
	Global::qsExternalPlayer     = m_pComboExternalPlayer->currentText ();
	Global::iDeleteTempOlderThan =-m_pEditOlderThan->text().toInt();
	if (m_pCheckDeleteOlder->isChecked ())
		Global::iDeleteTempOlderThan   = m_pEditOlderThan->text().toInt();

	pInit->setHistory  (m_iMaxHistoryFiles, m_listHistory, m_listHistoryPix);
	pInit->setAutosave (m_iAutosave);
	pInit->setStyle    (m_qsStyle);
	pInit->saveIniFile ();
	// after all's said and done, I can dump this object...
	delete pInit;

	// Okay if the user changes the Project name we might want to warn him that 
	// all temp data is to be lost ...
	if (m_pEditProjectName->text() != Global::qsProjectName)	{
		// Okay next we should check if there is some data in the prviouse temp directory...
		QString qsTempDir = Global::qsTempPath + QString ("/") + Global::qsProjectName;
		QDir tempDir (qsTempDir);
		if (tempDir.count() > 2)	{
			QString qsWarning = tr("Warning, there seem to be some temp data in %1/%2.\n\n").arg (Global::qsTempPath).arg(Global::qsProjectName);
			qsWarning += tr("[Yes] Move all temp data to %1/%2\n").arg(Global::qsTempPath).arg(m_pEditProjectName->text());
			qsWarning += tr("[Ok]  Leave everything as is,\n");
			qsWarning += tr("[No]  Delete all temp data under %1/%2\n").arg (Global::qsTempPath).arg(Global::qsProjectName);
			int iResult = MessageBox::warning (NULL, "Warning: Temp data", qsWarning, QMessageBox::Yes, QMessageBox::Ok, QMessageBox::No);
			if (iResult == QMessageBox::No)	{
				QString qsCommand = QString("rm -R %1/* ").arg(qsTempDir);
				if ( system (qsCommand) == -1 )
					return;
			}
			else if (iResult == QMessageBox::Yes)
				tempDir.rename (qsTempDir, QString ("%1/%2").arg(Global::qsTempPath).arg(m_pEditProjectName->text()));
		}
	}


	
	uiDialogSetup::accept();
}

void DialogSetup::resizeEvent (QResizeEvent *pResizeEvent)
{
	uiDialogSetup::resizeEvent(pResizeEvent);
	// Here we resize the widgets'n stuff to be as wide as possible ...
	if (m_pScrollFrame)	// Change width but not height ...
		m_pScrollFrame->resize (m_pScrollView->visibleWidth(), m_pScrollFrame->height());
}

void DialogSetup::slotImageButton(int)
{
	bool bCheck = m_pRadioMovieButton->isChecked();
	m_pGroupBox4->setEnabled (bCheck);
	m_pTimeEditStartOffset->setEnabled(bCheck);
	m_pTimeEditDuration   ->setEnabled(bCheck);
}

void DialogSetup::slotMovieButton(int)
{
	bool bCheck = m_pRadioMovieButton->isChecked();
	m_pGroupBox4->setEnabled (bCheck);
	m_pTimeEditStartOffset->setEnabled(bCheck);
	m_pTimeEditDuration   ->setEnabled(bCheck);
}

void DialogSetup::slotWithText(bool bChecked)
{
	m_pComboTextPosition->setEnabled(bChecked);
}

void DialogSetup::slotDeleteOlder(bool bChecked)
{
	m_pEditOlderThan->setEnabled(bChecked);
}

void DialogSetup::slotFont ()
{
	bool bOkay;
	QFont font = QFontDialog::getFont (&bOkay, (const QFont &)m_font, this, "Font_Dialog");
	if (bOkay)
		m_font = font;
}

void DialogSetup::slotColor ()
{
	QColor color = QColorDialog::getColor ( m_colorForeground, this, "Color_Dialog");
	if (color.isValid())
		m_colorForeground = color;
}

void DialogSetup::slotBrowseTemp ()
{
	// This function is called when the user clickes the Browse button next 
	// to the TempPath
	// This function will browse for the directory where the DVD is to be build.
	QString qsPathName = QFileDialog::getExistingDirectory ( m_pEditTempPath->text() );
	if  ( (qsPathName.isEmpty()) || (qsPathName.isNull()) )
		return;
	m_pEditTempPath->setText(qsPathName);
}

void DialogSetup::slotEngineInfo ()
{
	// This function will display some information about the chosen MediaEngine - class
	QString qsEngineInfo;
	qsEngineInfo = MediaCreator::getEngineDescription (comboPreferredEngine->currentText());

	QMessageBox::information (NULL, tr(""), qsEngineInfo, QMessageBox::Ok);
}

void DialogSetup::slotSetupEngine ()
{
	MediaInterface *pInterface = MediaCreator::createPreferredWidget (NULL, "ChapterXineWidget", NULL);
	// This is take care of in the polish () function for Xine and not necessary for MPlayer ...
	pInterface->initMediaEngine();
	pInterface->setupDialog ();

}

void DialogSetup::slotTabChanged(QWidget *)
{
	// Here we resize the widgets'n stuff to be as wide as possible ...
	if (m_pScrollFrame)	// Change width but not height ...
		m_pScrollFrame->resize (m_pScrollView->visibleWidth(), m_pScrollFrame->height());
}

void DialogSetup::slotResetHistory()
{
	// Remove the strings and pointer to the pixmaps.
	// Note: the pixmaps are going to get deleted in QDVDAuthor::slotSetup()
	m_listHistory.clear    ();
	m_listHistoryPix.clear ();
}

void DialogSetup::slotMaxHistoryChanged (int iNewMaxHistory)
{
	m_iMaxHistoryFiles = iNewMaxHistory;
}

void DialogSetup::slotAutosaveChanged (int iAutosave)
{
	m_iAutosave = iAutosave;
}

void DialogSetup::slotScanSystem()
{
	uint t, x;
	Utils theUtils;
	QValueList<Utils::toolsPaths *>listToolsPaths;
	// Here we generate the list to create the GUI widgets.
	listToolsPaths = theUtils.scanSystem();
	// Here we check all tools which were not be found if the user manually gave a path ...
	for (t=0;t<listToolsPaths.count();t++)	{
		// Okay we are only interested in the tolls not found by scanSystem.
		if (!listToolsPaths[t]->bPresent)	{
			for (x=0;x<m_listTools.count();x++)	{
				if (m_listTools[x] == listToolsPaths[t]->qsExecutableName)	{
					// and since m_listTools and m_listEditToolsPaths are synched ...
					QFileInfo fileInfo(m_listEditToolsPaths[x]->text());
					if (fileInfo.exists())	{
						listToolsPaths[t]->qsFullPath = m_listEditToolsPaths[x]->text();
						listToolsPaths[t]->bPresent = true;
					}
				}
			}
		}
	}
	// Next we can craete the GUI elements, and ...
	setToolsPaths (listToolsPaths);
	// then delete the created list-entries of the list.
	for (t=0;t<listToolsPaths.count();t++)
		delete listToolsPaths[t];
	m_bModifiedToolsPaths = true;
}

void DialogSetup::slotModifiedToolsPath(const QString &)
{
	m_bModifiedToolsPaths = true;
}

void DialogSetup::slotButtonMan ()
{
	// Here we handle the [Search ...] [man] button clicks.
	uint t;

	QButton *pObjectUnderMouse = NULL;
	for (t=0;t<m_listManButtons.count();t++)
	{
		// check if this button has the focus ...
		if ( (m_listManButtons[t]->hasMouse ()) || (m_listManButtons[t]->hasFocus()) )	{
			pObjectUnderMouse = m_listManButtons[t];
			break;
		}
	}
    if (pObjectUnderMouse != NULL)	{
		Utils theUtils;
		// Okay lets find out what this button stands for ...
		if (pObjectUnderMouse->text () == QString ("man"))
			displayMan (theUtils.getToolByIndex (m_listIndex[t]));
		else
			searchTool (theUtils.getToolByIndex (m_listIndex[t]));
	}
}

void DialogSetup::displayMan (QString qsTool)
{
	QStringList listTool;
	listTool.append(qsTool);
	
	QCursor myCursor (QCursor::WaitCursor);
	setCursor (myCursor);
	// Create a modeless dialog, so we can work with DialogExecute and the DialogMan at the same time.
	DialogMan *pManDialog = new DialogMan(listTool, this);
	pManDialog->show();
	myCursor = QCursor(QCursor::ArrowCursor);
	setCursor (myCursor);
}

void DialogSetup::searchTool (QString qsTool)
{
	uint t;
	int  i;
	QString qsFullPath = QFileDialog::getOpenFileName (QString ("./"), tr ("executable ( %1 );;All Files ( * )").arg(qsTool));
	if (qsFullPath.isEmpty())
		return;
	// Okay here we set the path
	Utils theUtils;
	i = theUtils.getIndexFromToolName (qsTool);
	if (i < 0)
		return;
	for (t=0;t<m_listIndex.count();t++)
		if ((int)m_listIndex[t] == i)
			break;

	m_listEditToolsPaths[t]->setText (qsFullPath);
	m_listEditToolsPaths[t]->setBackgroundColor (QColor (COLOR_ME_WHITE) );
	m_listManButtons[t]->setText("man");
	m_pScrollFrame->resize (m_pScrollView->visibleWidth(), m_pScrollFrame->height());
//	slotTabChanged(NULL);
}

void DialogSetup::slotButtonInfo()
{
	// Here we get the QObject * under the mouse pointer and check if it is in one of the buttons.
	// I prefer this approach over the QObject::sender() - function since this is a non-object oriented approach.
	// All external Tools are defined in global.h
	uint t;
	struct structTools { 
		char *pExecutableName;
		char *pDisplayName;
		char *pDescription;
	};
 	const structTools toolsArray[] = { EXTERNAL_TOOLS };
	//QObject *pObjectUnderMouse = sender();
	QButton *pObjectUnderMouse = NULL;
	for (t=0;t<m_listButtons.count();t++)
	{
		// check if this button has the focus ...
		if ( (m_listButtons[t]->hasMouse ()) || (m_listButtons[t]->hasFocus()) )	{
			pObjectUnderMouse = m_listButtons[t];
			break;
		}
	}
	if (!pObjectUnderMouse)	{
		MessageBox::warning(this, "Warning", "Say what ???", QMessageBox::Ok, QMessageBox::NoButton);
		return;
	}
	MessageBox::warning(this, QString( "Info tool : %1").arg(toolsArray[m_listIndex[t]].pExecutableName), toolsArray[m_listIndex[t]].pDescription, QMessageBox::Ok, QMessageBox::NoButton);
//	pToolLabel->setText (toolsArray[t].pDisplayName);
}

QValueList<Utils::toolsPaths *> DialogSetup::getToolsPathsList ()
{
	// Here we actually create the toolsPaths list before we return it ...
	
	// Warning, m_listTools has to have the same count as m_listIndex !!!
	uint t, iIndex;
	Utils::toolsPaths *pEntry;
	QValueList<Utils::toolsPaths *> listToolsPaths;
	// then we clear the list ...
//	for (t=0;t<m_listToolsPaths.count();t++)
//		delete m_listToolsPaths[t];
//	m_listToolsPaths.clear ();
	// I want to use the m_listIndex values to recreate the original order ...
	for (t=0;t<m_listTools.count();t++)	// should be same count as m_listEditToolsPaths ...
		listToolsPaths.append(new Utils::toolsPaths);
	// Okay and here we go through the current values ...
	for (t=0;t<listToolsPaths.count();t++)	{
		iIndex = m_listIndex[t];
		pEntry = listToolsPaths[iIndex];
		pEntry->qsExecutableName = m_listTools[iIndex];
		pEntry->qsFullPath = m_listEditToolsPaths[iIndex]->text();
		if (m_listEditToolsPaths[iIndex]->backgroundColor() == QColor (COLOR_ME_WHITE))
			pEntry->bPresent = true;
		else
			pEntry->bPresent = false;
	}

	QString qsPreferredEngine = comboPreferredEngine->currentText();
	MediaCreator::setPreferredEngine (qsPreferredEngine);
	// and then we can return ..
	return listToolsPaths;
}

