/***************************************************************************
                          mainwindow.cp  -  description
                             -------------------
    begin                : Sat Dec 1 2001
    copyright            : (C) 2001 by Richard Groult,
    				2003 OGINO Tomonori,
    				2004 Guillaume Duhamel
    email                : rgroult@jalix.org
    				ogino@nn.iij4u.or.jp
				guillaume.duhamel@univ-rouen.fr
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                                                  *
 *                                                                         *
 *   For license exceptions see LICENSE.EXC file, attached with the source *
 *   code.                                                                 *
 *                                                                         *
 ***************************************************************************/

#include "mainwindow.h"

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <math.h>
#include <stdlib.h>

// Local
#include "formatconversion.h"
#include "rename.h"
#include "mybookmarkmanager.h"
#include "confshowimg.h"
#include "imageviewer.h"
#include "extract.h"
#include "imagelistview.h"
#include "directoryview.h"
#include "directory.h"
#include "displayCompare.h"
#include "compressedfileitem.h"
#include "history_action.h"
#include "imagefileiconitem.h"
#include "imageloader.h"
#include "imagemetainfo.h"

#ifndef SHOWIMG_NO_CDARCHIVE
# include "cdarchive.h"
#endif

#ifdef HAVE_KIPI
#include "kipiplugins/kipipluginmanager.h"
#endif /* HAVE_KIPI */

// Qt
#include <qmessagebox.h>
#include <qregexp.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qmemarray.h>
#include <qdict.h>
#include <qkeycode.h>
#include <qdir.h>
#include <qtimer.h>
#include <qptrvector.h>
#include <qdatetime.h>
#include <qclipboard.h>
#include <qpainter.h>
#include <qdockarea.h>
#include <qtextcodec.h>

// KDE
#include <kaboutdata.h>
#include <khelpmenu.h>
#include <kio/job.h>
#include <kaboutapplication.h>
#include <ktoolbarbutton.h>
#include <kmessagebox.h>
#include <kaction.h>
#include <kstdaccel.h>
#include <kkeydialog.h>
#include <kedittoolbar.h>
#ifndef Q_WS_WIN
#include <konq_operations.h>
#endif
#include <kglobalsettings.h>
#include <kurlrequesterdlg.h>
#include <kdialogbase.h>
#include <kdockwidget.h>
#include <kcursor.h>
#include <kurldrag.h>
#include <kfiledialog.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kglobal.h>
#include <kconfig.h>
#include <kwin.h>
#include <ktoolbar.h>
#include <kdockwidget.h>
#include <kapplication.h>
#include <kbookmarkmanager.h>
#include <kbookmarkmenu.h>
#include <kbookmarkbar.h>
#include <kbookmark.h>
#include <kaccel.h>
#include <kstatusbar.h>
#include <kpopupmenu.h>
#include <kstandarddirs.h>
#include <kimageeffect.h>
#include <kscan.h>
#include <kprinter.h>
#include <kmenubar.h>
#include <kprogress.h>
#include <kfilemetainfo.h>
#include <kprocess.h>
#include <kcombobox.h>
#include <kurlrequester.h>
#include <kcompletion.h>
#include <kurlcompletion.h>
#include <kurldrag.h>
#include <kio/netaccess.h>
#include <ktip.h>
#include <ksqueezedtextlabel.h>

#define MYDEBUG kdDebug()<<__FILE__<<" " <<__LINE__ << " " << __FUNCTION__ << " "

const char* CONFIG_IMAGEVIEWER_GROUP = "imageviewer widget";
const char* CONFIG_DOCK_GROUP = "dock";
const char* CONFIG_BATCHRENAME = "batch rename";

class KDialogBase;

#define  PAS 32

/**
	a class to store datas to look for similaties of 2 images
*/
class ImageSimilarityData
{
public:
	ImageSimilarityData()
	{
		avg_r=(uchar*)malloc(PAS*PAS*sizeof(uchar));
		avg_g=(uchar*)malloc(PAS*PAS*sizeof(uchar));
		avg_b=(uchar*)malloc(PAS*PAS*sizeof(uchar));
	}

	~ImageSimilarityData()
	{
		delete(avg_r);
		delete(avg_g);
		delete(avg_b);
	}

	QString filename;

	uchar *avg_r;
	uchar *avg_g;
	uchar *avg_b;

	int filled;
	float ratio;
};






/**************************************************/


MainWindow::MainWindow (const QString& name)
	:KDockMainWindow (0, name.ascii()),
	KBookmarkOwner()

{
	init ();
	show();

	if(openDirType==0)
		openDir(QDir::homeDirPath());
	else
		openDir(openDirname);

	hasimageselected=TRUE;
	setHasImageSelected(imageList->hasImages());
}


MainWindow::MainWindow (const QString& pic, const QString& name)
	:KDockMainWindow (0, name.ascii()),
	KBookmarkOwner()
{
	init ();
	show();


	if (QFileInfo (pic).isDir() || QString(pic).right (3) == "sia")
	{
	    openDir(QDir (pic).absPath());

	    hasimageselected=TRUE;
	    setHasImageSelected(imageList->hasImages());
	}
	else
	if (Extract::canExtract(pic))
	{
		QString rep = QDir (pic).absPath ();
		int pos = rep.findRev ("/");
		openDir(rep.left (pos));

		hasimageselected=FALSE;
		setHasImageSelected(TRUE);

		imageList->setCurrentItemName(QFileInfo(pic).fileName());
		if (startFS) slotFullScreen();
		inInterface=FALSE;
	}
	else
	{
		QString rep = QDir (pic).absPath ();
		openDir(rep);

		hasimageselected=FALSE;
		setHasImageSelected(TRUE);
	}
}


MainWindow::~MainWindow ()
{
}


void
MainWindow::createHideShowAction(KDockWidget* dock) {
	QString caption;
	if (dock->mayBeHide()) {
		caption=i18n("Hide %1").arg(dock->caption());
	} else {
		caption=i18n("Show %1").arg(dock->caption());
	}

	KAction* action=new KAction(caption, 0, dock, SLOT(changeHideShowState()), actionCollection() );
	if (dock->icon()) {
		action->setIconSet( QIconSet(*dock->icon()) );
	}
	m_windowListActions.append(action);
}

void
MainWindow::createActions()
{
	m_actions =actionCollection();

	aBack		=new HistoryAction(i18n("Back"),"back", KStdAccel::shortcut(KStdAccel::Back).keyCodeQt(), this,SLOT(slotBack()), m_actions,"back");
	connect(aBack->popupMenu(), SIGNAL(activated(int)),this, SLOT(backMenuActivated(int)));
	connect(aBack->popupMenu(), SIGNAL( aboutToShow() ), SLOT( slotBackAboutToShow() ) );
	aBack->setEnabled(FALSE);

	aForward	=new HistoryAction(i18n("Forward"),"forward", KStdAccel::shortcut(KStdAccel::Forward).keyCodeQt() , this,SLOT(slotForward()), m_actions,"forward");
	connect(aForward->popupMenu(), SIGNAL(activated(int)),this, SLOT(forwardMenuActivated(int)));
	connect(aForward->popupMenu(), SIGNAL( aboutToShow() ), SLOT( slotForwardAboutToShow() ) );
	aForward->setEnabled(FALSE);

	//
	aCut		=new KAction(i18n("Cut"),"editcut", KStdAccel::shortcut(KStdAccel::Cut), this,SLOT(slotcut()),m_actions ,"editcut");
		aCut->setEnabled(FALSE);
	aCopy		=new KAction(i18n("Copy"),"editcopy", KStdAccel::shortcut(KStdAccel::Copy), this,SLOT(slotcopy()), m_actions,"editcopy");
	aCopyPixmap	=new KAction(i18n("Copy Image"), 0, this,SLOT(slotcopyPixmap()), m_actions,"editcopypixmap");
	aPaste		=new KAction(i18n("Paste"),"editpaste", KStdAccel::shortcut(KStdAccel::Paste), this,SLOT(slotpaste()),m_actions,"editpaste" );

	//
	aGoHome		=new KAction(i18n("Go to &Home Directory"), "gohome", KStdAccel::shortcut(KStdAccel::Home), this, SLOT(goHome()),m_actions ,"goHome");
	aGoUp		=new KAction(i18n("Go Up"), "up", KStdAccel::shortcut(KStdAccel::Up), this, SLOT(goUp()),m_actions ,"goUp");

	aPrevious	=new KAction(i18n("Previous Image"),"1leftarrow", Key_PageUp, imageList,SLOT(previous()),m_actions,"Previous Image" );
	aNext		=new KAction(i18n("Next Image"),"1rightarrow", Key_PageDown, imageList,SLOT(next()), m_actions,"Next Image");

	aFirst		=new KAction(i18n("First Image"),"top", KStdAccel::shortcut(KStdAccel::Home), imageList,SLOT(first()),m_actions,"First Image" );
	aLast		=new KAction(i18n("Last Image"),"bottom", KStdAccel::shortcut(KStdAccel::End),imageList ,SLOT(last()),m_actions,"Last Image" );

	aPreviousDir	=new KAction(i18n("Previous Directory"), KShortcut(SHIFT+Key_Space), dirView, SLOT(goToPreviousDir()),m_actions,"Previous Directory" );
	aNextDir	=new KAction(i18n("Next Directory"), KShortcut(CTRL+Key_Space), dirView, SLOT(goToNextDir()), m_actions,"Next Directory");

	KActionMenu *actionGo = new KActionMenu( i18n("&Go"),m_actions, "action go");
	actionGo->insert(aGoUp);
	actionGo->insert(aGoHome);
	actionGo->insert(new KActionSeparator());
	actionGo->insert(aPreviousDir);
	actionGo->insert(aNextDir);
	actionGo->insert(new KActionSeparator());
	actionGo->insert(aPrevious);
	actionGo->insert(aNext);
	actionGo->insert(aFirst);
	actionGo->insert(aLast);


	//
	aNewWindow	=new KAction(i18n("New Window"),"window_new", KStdAccel::shortcut(KStdAccel::New), this, SLOT(slotNewWindow()),m_actions,"window_new" );


	aOpenLocation	=new KAction(i18n("Open Location"),"fileopen", KStdAccel::shortcut(KStdAccel::Open), this, SLOT(slotOpenLocation()),m_actions,"fileopen" );

	aSaveImage	=new KAction(i18n("Save &As..."),"filesave", KStdAccel::shortcut(KStdAccel::Save), this, SLOT(slotSaveImage()),m_actions,"filesave" );

	//aQuit		=new KAction(i18n("Quit"),"exit", KStdAccel::shortcut(KStdAccel::Quit), kapp, SLOT(quit()),m_actions ,"exit");
	aQuit = KStdAction::quit( kapp, SLOT (closeAllWindows()), actionCollection() );
	aClose		=new KAction(i18n("Close"),"fileclose", KStdAccel::shortcut(KStdAccel::Close), this, SLOT(close()),m_actions ,"close");
	//
	aUndo		=new KAction(i18n("Undo"),"undo", KStdAccel::shortcut(KStdAccel::Undo), this, SLOT(slotUndo()),m_actions ,"undo");
	aUndo->setEnabled(FALSE);
	aRedo		=new KAction(i18n("Redo"),"redo", KStdAccel::shortcut(KStdAccel::Redo), this, SLOT(slotRedo()),m_actions ,"redo");
	aRedo->setEnabled(FALSE);

	//
	aRename		=new KAction(i18n("Rename File..."),"item_rename", KShortcut(Key_F2), imageList, SLOT(slotRename()),m_actions ,"rename");
	aDelete		=new KAction(i18n("Delete File"),"editdelete", KShortcut(SHIFT+Key_Delete), imageList,SLOT(slotSupprimmer()), m_actions,"editdelete");
	aTrash		=new KAction(i18n("Move File to Trash"),"edittrash", KShortcut(Key_Delete), imageList,SLOT(slotMoveToTrash()), m_actions,"edittrash");
	aShred		=new KAction(i18n("Shred File"),"editshred", KShortcut(SHIFT+CTRL+Key_Delete), imageList,SLOT(slotShred()), m_actions,"editshred");

	aEditType	=new KAction(i18n("Edit File Type"), 0, this,SLOT(slotEditFileType()), m_actions,"Edit File Type");
	aFileProperties	=new KAction(i18n("Properties"), 0, imageList,SLOT(slotFileProperty()), m_actions,"Properties");
	aImageInfo	=new KAction(i18n("Image Info"), 0, imageList,SLOT(slotImageInfo()), m_actions,"Image Info");
	aDirInfo	=new KAction(i18n("Describe Directory..."), 0, dirView,SLOT(slotDirInfo()), m_actions,"Dir Info");
	aDirProperties	=new KAction(i18n("Properties"), 0, dirView, SLOT(slotDirProperty()), m_actions,"Dir Properties");

	aSelect		=new KAction(i18n("Select All"), KStdAccel::shortcut(KStdAccel::SelectAll) , imageList,SLOT(slotSelectAll()), m_actions,"SelectAll");
	aUnselectAll	=new KAction(i18n("Unselect All"),0, imageList ,SLOT(slotUnselectAll()), m_actions,"Unselect All");
	aInvertSelection=new KAction(i18n("Invert Selection"), KShortcut(CTRL+Key_I),imageList ,SLOT(slotInvertSelection()), m_actions,"Invert Selection");

	aConfigureKey =     KStdAction::keyBindings(this, SLOT(configureKey()), 		actionCollection() );
	aConfigureToolbars= KStdAction::configureToolbars(this, SLOT(configureToolbars()),	actionCollection() );
	aConfigureShowImg = KStdAction::preferences(this, SLOT(configureShowImg()), 		actionCollection() );
	// the tip action
	(void)KStdAction::tipOfDay(this, SLOT(slotShowTips()), actionCollection(), "help_showimgtipofday");

	//
	aRenameSeries	=new KAction(i18n("&Rename Series..."), "item_rename", 0, this,SLOT(renameSeries()), m_actions,"Rename series");
	aSlideshow	=new KToggleAction(i18n("&Slide Show"),"run", 0, this,SLOT(slotSlideShow()), m_actions,"Slideshow");

	//
	aReloadDir	=new KAction(i18n("Refresh"),"reload", KStdAccel::shortcut(KStdAccel::Reload), this,SLOT(slotRefresh()), m_actions,"Refresh");
	aPreview	=new KToggleAction(i18n("Toggle Thumbnails"),"thumbnail", 0, this,SLOT(slotPreview()), m_actions,"Preview");
	aStop		=new KAction(i18n("Stop"),"stop", 0, this,SLOT(slotStop()), m_actions,"Stop");
	aStop->setEnabled(FALSE);

	//
	aIconSmall	=new KRadioAction(i18n("Small Icons"),"smallthumbnails", 0, this,SLOT(slotIconSize()), m_actions,"Small Icons");
	aIconMed	=new KRadioAction(i18n("Medium Icons"),"medthumbnails", 0, this,SLOT(slotIconSize()), m_actions,"Medium Icons");
	aIconBig	=new KRadioAction(i18n("Large Icons"),"largethumbnails", 0, this,SLOT(slotIconSize()), m_actions,"Big Icons");
	aIconSmall->setExclusiveGroup("IconSize");
	aIconMed->setExclusiveGroup("IconSize");aIconMed->setChecked(TRUE);
	aIconBig->setExclusiveGroup("IconSize");
	KActionMenu *actionIconSize = new KActionMenu( i18n("Icon Size"), "medthumbnails", m_actions, "view_icons" );
	actionIconSize->insert(aIconSmall);
	actionIconSize->insert(aIconMed);
	actionIconSize->insert(aIconBig);

	////
	KShortcut sc_fs(CTRL+Key_F); sc_fs.append(KKeySequence((const KKey&)(CTRL+Key_Return)));
	aFullScreen	=new KToggleAction(i18n("Full Screen"),"window_fullscreen", sc_fs, this, SLOT(slotFullScreen()),m_actions,"FullScreen" );
	aFullScreen->setChecked(FALSE);

	//
	aSortByName	=new KRadioAction(i18n("By Name"), 0, imageList,SLOT(slotByName()), m_actions,"by name");
	aSortByType	=new KRadioAction(i18n("By Type"), 0, imageList,SLOT(slotByExtension()), m_actions,"by extension");
	aSortBySize	=new KRadioAction(i18n("By Size"), 0, imageList,SLOT(slotBySize()), m_actions,"by size");
	aSortByDate	=new KRadioAction(i18n("By Date"), 0, imageList,SLOT(slotByDate()), m_actions,"by date");
	aSortByDirName	=new KRadioAction(i18n("By Path && Name"), 0, imageList,SLOT(slotByDirName()), m_actions,"by dir name");
	aSortByName->setExclusiveGroup("sort mode");
	aSortByType->setExclusiveGroup("sort mode");
	aSortBySize->setExclusiveGroup("sort mode");
	aSortByDate->setExclusiveGroup("sort mode");
	aSortByDirName->setExclusiveGroup("sort mode");
	aSortByName->setChecked(TRUE);
	KActionMenu *actionSortMenu = new KActionMenu( i18n("Sort"), m_actions, "view_sort" );
	actionSortMenu->insert(aSortByName);
	actionSortMenu->insert(aSortByType);
	actionSortMenu->insert(aSortBySize);
	actionSortMenu->insert(aSortByDate);
	actionSortMenu->insert(new KActionSeparator());
	actionSortMenu->insert(aSortByDirName);

	//
	aOpenWithGimp	=new KAction(i18n("Open with &Gimp"),"gimp", 0, imageList,SLOT(slotGimp()), m_actions,"Open with Gimp");
	aOpenWithKhexedit=new KAction(i18n("Open with &Khexedit"),"khexedit", 0, imageList,SLOT(slotKhexedit()), m_actions,"Open with Khexedit");
	aOpenWith	=new KAction(i18n("&Other..."), 0, imageList,SLOT(slotOpenWith()), m_actions,"Open with");

	KActionMenu *actionNewItems = new KActionMenu( i18n("Create &New"), m_actions, "create_new_items" );
	aDirNewFolder	=new KAction(i18n("New Directory..."),"folder_new", 0, dirView, SLOT(slotNewDir()),m_actions ,"editdirnew");
	actionNewItems->insert(aDirNewFolder);
	aDirNewAlbum	=new KAction(i18n("New Album..."),"txt", 0, dirView, SLOT(slotNewAlbum()),m_actions ,"editalbumnew");
	actionNewItems->insert(aDirNewAlbum);
#ifndef SHOWIMG_NO_CDARCHIVE
	aDirNewCDArchive=new KAction(i18n("New CD Archive..."),"cdimage", 0, dirView, SLOT(slotNewCDArchive()),m_actions ,"editnewcdarchive");
	actionNewItems->insert(aDirNewCDArchive);
#endif

	//aDirCut		=new KAction(i18n("Cut"),"editcut", 0, this,SLOT(slotDirCut()),m_actions ,"editdircut");
	aDirCopy	=new KAction(i18n("Copy Folder To..."),"editcopy", 0, dirView, SLOT(slotDirCopy()),m_actions ,"editdircopy");
	aDirMove	=new KAction(i18n("Move Folder To..."), 0, dirView, SLOT(slotDirMove()),m_actions ,"editdirmove");
	//aDirPaste	=new KAction(i18n("Paste"),"editpaste", 0, this,SLOT(slotDirPaste()),m_actions ,"editdirpaste");
	aDirPasteFiles	=new KAction(i18n("Paste Files"),"editpaste", 0, dirView, SLOT(slotDirPasteFiles()),m_actions ,"editdirpaste files");
	aDirRecOpen	=new KAction(i18n("Recursively Open"), 0, dirView, SLOT(recursivelyOpen()), m_actions ,"dirRecOpen");

	aDirRename=new KAction(i18n("&Rename Item..."),"item_rename", 0, dirView,SLOT(slotRename()),m_actions ,"editdirrename");

	aDirTrash=new KAction(i18n("&Move Item to Trash"),"edittrash", 0, dirView,SLOT(slotTrash()),m_actions ,"editdirtrash");
	aDirDelete=new KAction(i18n("&Delete"),"editdelete", 0, dirView,SLOT(slotSuppr()),m_actions ,"editdirdelete");

	aFilesMoveTo	=new KAction(i18n("Move Files To..."), 0, imageList,SLOT(slotFilesMoveTo()),m_actions ,"moveFilesTo");
	aFilesCopyTo	=new KAction(i18n("Copy Files To..."), 0, imageList, SLOT(slotFilesCopyTo()),m_actions ,"copyFilesTo");

	aScrollXR	=new KAction(i18n("Scroll on the Right"), Key_Right, iv, SLOT(scrolldxR()),m_actions ,"ScrollXR");
	aScrollYB	=new KAction(i18n("Scroll at the Bottom"),Key_Down , iv, SLOT(scrolldyB()),m_actions ,"ScrollYB");
	aScrollXL	=new KAction(i18n("Scroll on the Left"), Key_Left, iv, SLOT(scrolldxL()),m_actions ,"ScrollXL");
	aScrollYT	=new KAction(i18n("Scroll on the Top"), Key_Up, iv, SLOT(scrolldyT()),m_actions ,"ScrollYT");

	aCovert		=new KAction(i18n("Format Conversion..."), 0, this,SLOT(convert()), m_actions,"convert");
	aToolsRotateLeft=new KAction(i18n("Rotate &Left"), "rotation_acw_file", CTRL+Key_L, this, SLOT(toolsRotateLeft()),m_actions ,"aToolsRotateLeft");
	aToolsRotateRight=new KAction(i18n("Rotate &Right"), "rotation_cw_file", CTRL+Key_R, this, SLOT(toolsRotateRight()),m_actions ,"aToolsRotateRight");
	KActionMenu *actionConv = new KActionMenu( i18n("Convert"), m_actions, "tools_conv" );
	actionConv->insert(aCovert);
	actionConv->insert(aToolsRotateLeft);
	actionConv->insert(aToolsRotateRight);


	aUpdateCache	=new KAction(i18n("Recursively &Update Current Cached Thumbails"), 0, this, SLOT(updateCache()),m_actions ,"updateCache");
	aClearCacheRec	=new KAction(i18n("Recursively Remove Current Cached Thumbails"),  0, this, SLOT(clearCacheRec()),m_actions ,"clearCacheRec");
	aClearCache	=new KAction(i18n("&Remove Current Cached Thumbails"),  0, this, SLOT(clearCache()),m_actions ,"clearCache");
	KActionMenu *actionMaint = new KActionMenu( i18n("Main&tenance"), m_actions, "tools_maint" );
	actionMaint->insert(aUpdateCache);
	actionMaint->insert(aClearCacheRec);
	actionMaint->insert(aClearCache);


	/////////
	iv->initActions(m_actions);

	//////
	abookmarkmenu = 	new KActionMenu(i18n("&Bookmark"), m_actions, "bookm");
	mBookMenu=		new KBookmarkMenu(MyBookmarkManager::self(),this, abookmarkmenu->popupMenu(),  m_actions, TRUE);

#ifndef HAVE_KIPI
	aCompareFast	=new KAction(i18n("&Exact Comparison"), 0, this,SLOT(slotCompareFast()), m_actions,"Compare fast");
	aCompareAlmost	=new KAction(i18n("&Approximate Comparison"), 0, this,SLOT(slotCompareAlmost()), m_actions,"Compare almost");
	KActionMenu *actionCmp = new KActionMenu( i18n("&Find Images"), BarIcon ("filefind", 16), m_actions, "tools_campare" );
	actionCmp->insert(aCompareFast);
	actionCmp->insert(aCompareAlmost);

#ifndef SHOWIMG_NO_SCAN_IMAGE
	aScan	=new KAction(i18n("Scan Image..."),  "scanner", 0, this, SLOT(slotScanImage()),m_actions ,"scanimage");
#endif
	aWallpaper_CENTER	=new KAction(i18n("Centered"), 0, iv, SLOT(wallpaperC()), m_actions,"Center");
	aWallpaper_MOSAIC	=new KAction(i18n("Tiled"), 0, iv, SLOT(wallpaperM()), m_actions,"Mosaic");
	aWallpaper_CENTER_MOSAIC=new KAction(i18n("Center Tiled"), 0, iv, SLOT(wallpaperCM()), m_actions,"Center adapt");
	aWallpaper_CENTER_MAX	=new KAction(i18n("Centered Maxpect"), 0, iv, SLOT(wallpaperCMa()), m_actions,"Center max");
	aWallpaper_ADAPT	=new KAction(i18n("Scaled"), 0, iv, SLOT(wallpaperA()), m_actions,"Adapt");
	aWallpaper_LOGO		=new KAction(i18n("Logo"), 0, iv, SLOT(wallpaperL()), m_actions,"Logo");
	KActionMenu *actionWallp = new KActionMenu( i18n("Set as Wallpaper"), "desktop",m_actions, "view_wallp" );
	actionWallp->insert(aWallpaper_CENTER);
	actionWallp->insert(aWallpaper_MOSAIC);
	actionWallp->insert(aWallpaper_CENTER_MOSAIC);
	actionWallp->insert(aWallpaper_CENTER_MAX);
	actionWallp->insert(aWallpaper_ADAPT);
	actionWallp->insert(aWallpaper_LOGO);
#endif /* HAVE_KIPI */

  //
	m_URLHistory=new KHistoryCombo(this);
	m_URLHistory->setDuplicatesEnabled(FALSE);
	m_URLHistory->setAutoDeleteCompletionObject(TRUE);

	m_URLHistoryCompletion=new KURLCompletion(KURLCompletion::DirCompletion);
	m_URLHistory->setCompletionObject(m_URLHistoryCompletion);
	m_URLHistoryCompletion->setDir("file:/");

	KWidgetAction* comboAction=new KWidgetAction( m_URLHistory, i18n("Location Bar"), 0, 0, 0, m_actions, "location_url");
	comboAction->setShortcutConfigurable(FALSE);
	comboAction->setAutoSized(TRUE);

	(void)new KAction( i18n("Clear Location Bar"),"locationbar_erase", 0, m_URLHistory, SLOT(clearEdit()), m_actions, "clear_location");

	QLabel* m_urlLabel=new QLabel(i18n("L&ocation:"), this, "kde toolbar widget");
	(void)new KWidgetAction( m_urlLabel, i18n("L&ocation:"), 0, 0, 0, m_actions, "location_label");
	m_urlLabel->setBuddy(m_URLHistory);
	aGo     =       new KAction(i18n("Go"), "key_enter", 0, this, SLOT(changeDirectory()), actionCollection(), "location_go");

	connect(m_URLHistory, SIGNAL(returnPressed()), this, SLOT(changeDirectory()));

  //
	m_zoomCombo=new KComboBox(/*this*/);
	m_zoomCombo->insertItem("10 %"); m_zoomCombo->insertItem("25 %"); m_zoomCombo->insertItem("33 %");
	m_zoomCombo->insertItem("50 %"); m_zoomCombo->insertItem("67 %"); m_zoomCombo->insertItem("75 %");
	m_zoomCombo->insertItem("100 %"); m_zoomCombo->insertItem("150 %"); m_zoomCombo->insertItem("200 %");
	m_zoomCombo->insertItem("300 %"); m_zoomCombo->insertItem("400 %"); m_zoomCombo->insertItem("600 %");
	m_zoomCombo->insertItem("800 %"); m_zoomCombo->insertItem("1000 %"); m_zoomCombo->insertItem("1200 %");
	m_zoomCombo->insertItem("1600 %"); m_zoomCombo->setEditable ( true );
	m_zoomCombo->setInsertionPolicy ( QComboBox::NoInsertion );
	m_zoomCombo->setDuplicatesEnabled( false );
	
	//FIXME "Zoom"->i18n("Zoom")
	KWidgetAction* zoomComboAction=new KWidgetAction( m_zoomCombo, "Zoom",
							 0, 
							 0, 0, 
							 m_actions, "zoomComboAction");
	zoomComboAction->setShortcutConfigurable(FALSE);
	zoomComboAction->setAutoSized(false);
	connect(m_zoomCombo, SIGNAL(activated ( const QString& )), this, SLOT(setZoom( const QString& )));

	//
#ifdef HAVE_LIBKEXIF
	aDisplayExifInformation	=new KAction(i18n("Exif Information"), 0, imageList, SLOT(slotDisplayExifInformation()), m_actions, "files_Display_Exif_Information");
#else
	#ifdef __GNUC__
	#warning no HAVE_LIBKEXIF
	#endif
	aDisplayExifInformation = NULL;
#endif /* HAVE_LIBKEXIF */

 	// Non configurable stop-fullscreen accel
	QAccel* accel=new QAccel(this);
	accel->connectItem(accel->insertItem(Key_Escape),this,SLOT(escapePressed()));
	accel->connectItem(accel->insertItem(Key_Space),this,SLOT(spacePressed()));

	// Dock related
	connect(manager(), SIGNAL(change()),
		this, SLOT(updateWindowActions()) );
}

void
MainWindow::updateWindowActions() {
	unplugActionList("winlist");
	m_windowListActions.clear();
	createHideShowAction(dockIL);
	createHideShowAction(dockIV);
	createHideShowAction(dockDir);
	createHideShowAction(dockIMI);
	plugActionList("winlist", m_windowListActions);
}

void
MainWindow::createAccels()
{
	m_actions->readShortcutSettings( QString::null );
	mAccel = m_actions->accel();

	imageList->initMenu(m_actions);
	dirView->initMenu(m_actions);
	iv->initMenu(m_actions);
}



void
MainWindow::setActionsEnabled(bool enable)
{
	int count=m_actions->count();
	for (int pos=0;pos<count;++pos)
		m_actions->action(pos)->setEnabled(enable);

}

void
MainWindow::slotIconSize(bool refresh)
{
	slotStop();
	if(aIconSmall->isChecked())
	{
		imageList->setThumbnailSize(QSize(80, 60), refresh);
	}
	else
	if(aIconMed->isChecked ())
	{
		imageList->setThumbnailSize(QSize(128, 96), refresh);

	}
	else
	if(aIconBig->isChecked ())
	{
		imageList->setThumbnailSize(QSize(160, 120), refresh);
	}
	if(refresh) slotRefresh ();
}


#define SB_ITEMS    1
#define SB_SCALE    2
#define SB_NAME     3
#define SB_TYPE     4
#define SB_IMG_SIZE 5
#define SB_BYTES    6
#define SB_DATE     7
#define SB_MSG      8
#define SB_PATH     9

void
MainWindow::createStatusbar()
{
	statusBar()->insertItem(QString::null, SB_MSG, 1,TRUE);		statusBar()->setItemAlignment(SB_MSG, AlignTop);
	statusBar()->insertItem(QString::null, SB_ITEMS, 0,TRUE);		statusBar()->setItemAlignment(SB_ITEMS, AlignTop|AlignHCenter);
	statusBar()->insertItem(QString::null, SB_SCALE, 0,TRUE);		statusBar()->setItemAlignment(SB_SCALE, AlignTop|AlignHCenter);

	SB_NAME_Label = new KSqueezedTextLabel (statusBar());
	SB_NAME_Label->setAlignment( int( KSqueezedTextLabel::AlignCenter ) );
	statusBar()->addWidget (SB_NAME_Label, 2, TRUE);

	statusBar()->insertItem(QString::null, SB_TYPE, 0,TRUE);		statusBar()->setItemAlignment(SB_TYPE, AlignTop|AlignHCenter);
	statusBar()->insertItem(QString::null, SB_IMG_SIZE, 1,TRUE);	statusBar()->setItemAlignment(SB_IMG_SIZE, AlignTop|AlignHCenter);
	statusBar()->insertItem(QString::null, SB_BYTES, 1,TRUE);		statusBar()->setItemAlignment(SB_BYTES, AlignTop|AlignHCenter);

	SB_DATE_Label = new KSqueezedTextLabel (statusBar());
	SB_DATE_Label->setAlignment( int( KSqueezedTextLabel::AlignCenter ) );
	statusBar()->addWidget (SB_DATE_Label, 2, TRUE);

	progress = new KProgress (statusBar(), "QProgressBar de chargement des images de MainWindow");
	progress->setCenterIndicator (TRUE);
	statusBar()->addWidget (progress, 1, FALSE);
	progress->hide();

}
void
MainWindow::setMessage(const QString& msg)
{
	statusBar()->changeItem(msg,SB_MSG);
}


void
MainWindow::setImageIndex (int index)
{
	imageIndex=index;
	setNbrItems(nbrItems);
}

void
MainWindow::setNbrItems (int nbr)
{
	nbrItems=nbr;

	QString msg;
	if(nbr==0)
		msg =i18n("no item");
	else
	if(imageIndex>=0&&!dirView->showAllFile()&&!dirView->showDir())
		msg =i18n("%2/%n item","%2/%n items", nbrItems).arg(imageIndex+1);
	else
		msg =i18n("%n item", "%n items", nbrItems);

	statusBar()->changeItem(" "+msg+" ", SB_ITEMS);
}

void
MainWindow::setZoom (float zoom)
{
	QString nb; nb.setNum(zoom,'f',0);
	statusBar()->changeItem(QString(" %1% ").arg(nb), SB_SCALE );
	m_zoomCombo->disconnect( SIGNAL( activated ( const QString& ) ) );
	m_zoomCombo->setCurrentText(nb + " %");
	connect(m_zoomCombo, SIGNAL(activated ( const QString& )), this, SLOT(setZoom( const QString& )));
}

void 
MainWindow::setZoom ( const QString& val)
{
	QRegExp reg("(\\d*)");
	reg.search(val);
	QStringList list = reg.capturedTexts();
	bool ok;
	float v = QString(list[1]).toInt(&ok);
	if(ok)	
		iv->setZoomValue(v/100);
}

void
MainWindow::setImagename (const QString& name)
{
	SB_NAME_Label->setText(name);
}

void
MainWindow::setImagetype (const QString& type)
{
	statusBar()->changeItem(" "+type.upper()+" ",SB_TYPE );
}


void
MainWindow::setDim (const QSize& size, float dpi)
{
	if(!size.isEmpty())
	{
		QString msg;
		statusBar()->changeItem(QString("%1 x %2 (%3 dpi) ")
				.arg(size.width())
				.arg(size.height())
				.arg((int)(dpi!=0?ceil(dpi):72)),
			SB_IMG_SIZE );
	}
	else
		statusBar()->changeItem(QString::null, SB_IMG_SIZE );
}

void
MainWindow::setSize (int size)
{
	if(size>=0)
	{
		statusBar()->changeItem(QString("%1").arg(KGlobal::locale()->formatNumber(size, 0)), SB_BYTES);
	}
	else
		statusBar()->changeItem(QString::null, SB_BYTES);
}

void
MainWindow::setDate (QDateTime *date)
{
	if(!date)
		setDate(QString::null);
	else
		setDate(KGlobal::locale()->formatDateTime(*date, FALSE));
}
void
MainWindow::setDate (const QString& date)
{
	SB_DATE_Label->setText(date);
}


void
MainWindow::changeDirectory()
{
       KURL url = KURL(m_URLHistoryCompletion->replacedPath(m_URLHistory->currentText()));
       if (!url.protocol().compare("http") || !url.protocol().compare("ftp"))
       {
		QString tmpFile = locateLocal("tmp", "showimg-net/");
		tmpFile += url.filename();
#if  KDE_VERSION >= 0x30200
		if( KIO::NetAccess::download( url, tmpFile, this ) )
#else
		if( KIO::NetAccess::download( url, tmpFile ) )
#endif
		{
		       openDir(tmpFile);
		       //KIO::NetAccess::removeTempFile( tmpFile );
		}
		else
		{
			openDir(currentDir());
		}
       }
       else
       {
	       openDir(url.path());
       }
}


void
MainWindow::forwardMenuActivated(int item)
{
	go(aForward->popupMenu()->indexOf(item)+1);
}


void
MainWindow::createMainView()
{
	manager()->setSplitterHighResolution(TRUE);
	manager()->setSplitterOpaqueResize(TRUE);

	///
	dockIL = createDockWidget ("Directory", BarIcon("folder", 16), 0L, i18n("Directory"), i18n("Directory"));
	imageList = new ImageListView (dockIL, "ImageList", this);
	QWhatsThis::add(imageList, i18n( "Images of the selected directories" ) );
	dockIL->setWidget(imageList);
	dockIL->setToolTipString(i18n("Images in the selected directories"));

	dockIV = createDockWidget ("Preview", BarIcon("image", 16),0L, i18n("Preview"), i18n("Preview"));
	iv = new ImageViewer (dockIV, imageList, this, "ImageViewer");
	dockIV->setWidget( iv );
	KCursor::setAutoHideCursor(iv, TRUE);
	QWhatsThis::add(iv, i18n( "Image preview" ) );
	dockIV->setToolTipString(i18n("Image preview"));

	dockDir = createDockWidget ("Tree", BarIcon("view_tree", 16),0L, i18n("Treeview"), i18n("Treeview"));
	dirView = new DirectoryView (dockDir, iv, imageList, this);
	QWhatsThis::add(dirView, i18n( "List of directories" ) );
	dockDir->setWidget( dirView );
	dockDir->setToolTipString(i18n("The directory tree"));

	dockIMI = createDockWidget ("Image Meta Data", BarIcon("image"),0L, i18n("Image Meta Data"), i18n("Image Meta Data"));
	imageMetaInfo = new ImageMetaInfo(dockIMI);
	dockIMI->setWidget( imageMetaInfo );
	dockIMI->resize(100,100);

	///
	setMainDockWidget( dockIV );
	setView (dockIV);

	dockDir->manualDock(dockIV, KDockWidget::DockLeft, 35);
	dockIL->manualDock(dockDir, KDockWidget::DockBottom, 35);
	dockIMI->manualDock(dockIV, KDockWidget::DockBottom, 35);

	/////////
	root = new Directory (dirView, iv, imageList, this);
	root->setOpen (TRUE);

#ifndef SHOWIMG_NO_CDARCHIVE
	cdArchiveRoot = new CDArchive (dirView, iv, imageList, this);
	cdArchiveRoot->setOpen (TRUE);
#endif

	dirView->setRootIsDecorated(TRUE);
}


void
MainWindow::init ()
{
	total = 0;
	done = 0;
	inFullScreen = FALSE;
	inInterface=FALSE;
#ifndef SHOWIMG_NO_SCAN_IMAGE
	m_scanDialog=NULL;
#endif
	m_renameS=NULL;
	formatConver=NULL;
	deleteTempDirectoriesDone_=FALSE;

	config = KGlobal::config();

	createMainView();
	createStatusbar();
	setStandardToolBarMenuEnabled(TRUE);
	createActions();
		aTime = new KAction(QString::null, (const KShortcut&)0, this, SLOT(slotDisplayNBImg()), m_actions,"time");
	createAccels();
	createGUI("showimgui.rc", FALSE);

	KMainWindow::applyMainWindowSettings(config, "MainWindow");
	m_windowListActions.setAutoDelete(TRUE);
	updateWindowActions();


#ifdef HAVE_KIPI
	// Load Plugins
	pluginManager_ = new KIPIPluginManager(this);
	pluginManager_->loadPlugins();
#endif /* HAVE_KIPI */

	iv->readConfig(config, CONFIG_IMAGEVIEWER_GROUP);
	readDockConfig (config, CONFIG_DOCK_GROUP);
	readConfig(config);
	restoreWindowSize(config);
}


void
MainWindow::readConfig(KConfig *config)
{
	config->setGroup("Options");
	aPreview->setChecked(config->readBoolEntry("preview", FALSE));
	imageList->il->setStoreThumbnails(config->readBoolEntry("storeth", TRUE));
	showFrame=config->readBoolEntry("showFrame", TRUE);
	imageList->il->setShowFrame(showFrame);

	imageList->setWordWrapIconText(config->readBoolEntry("WordWrapIconText", TRUE));
	imageList->setShowMimeType(config->readBoolEntry("ShowMimeType", FALSE));
	imageList->setShowSize(config->readBoolEntry("ShowSize", TRUE));
	imageList->setShowDate(config->readBoolEntry("ShowDate", FALSE));
	imageList->setShowDimension(config->readBoolEntry("ShowDimension", FALSE));
	imageList->setShowToolTips(config->readBoolEntry("ShowToolTips", TRUE));

	imageList->setPreloadIm(config->readBoolEntry("preloadIm", TRUE));
	imageList->setShowMeta(config->readBoolEntry("showMeta", TRUE));
	imageList->setShowHexa(config->readBoolEntry("showHexa", TRUE));
	dirView->setShowHiddenDir(config->readBoolEntry("showhiddenDir", FALSE));
	dirView->setShowHiddenFile(config->readBoolEntry("showhiddenFile", FALSE));
	dirView->setShowDir(config->readBoolEntry("showDir", TRUE));
	dirView->setShowAllFile(config->readBoolEntry("showallFile", FALSE));
	dirView->setLoadFirstImage(config->readBoolEntry("loadFirstImage", TRUE));
	slotIconSize();
	aTime->setText(i18n("%1 images seen").arg(iv->nbImg));

	config->setGroup("Slideshow");
	slideshowTime=config->readNumEntry("time", 2);
	slideshowType=config->readNumEntry("type", 0);
	imageList->setLoop(config->readBoolEntry("loop", false));

	config->setGroup("confirm");
	openDirType=config->readNumEntry("openDirType", 0);
	openDirname=config->readPathEntry("openDirname", QDir::homeDirPath());
	showSP=config->readBoolEntry("showSP", TRUE);
	startFS=config->readBoolEntry("startFS", TRUE);
	imageList->il->setUseEXIF(iv->useEXIF());
	showToolbar=config->readBoolEntry("showToolbar", FALSE);
	showStatusbar=config->readBoolEntry("showStatusbar", FALSE);


	config->setGroup("Paths");
	cdromPath = config->readPathEntry("cdromPath", "/mnt/cdrom");
	imageList->setgimpPath(config->readPathEntry("gimpPath", "gimp-remote -n"));
	convertPath = config->readPathEntry("convertPath", "convert");
	jpegtranPath = config->readPathEntry("jpegtranPath", "jpegtran");


	timer = new QTimer (this);
	if(slideshowType == 0 )
		connect (timer, SIGNAL (timeout ()), imageList, SLOT (next ()));
	else
		connect (timer, SIGNAL (timeout ()), imageList, SLOT (previous()));

	config->setGroup("TipOfDay");
	if(config->readBoolEntry("RunOnStart", TRUE))
		slotShowTips();
}
void
MainWindow::writeConfig(KConfig *config)
{
	/////
	config->setGroup("Options");

	config->writeEntry( "preview", aPreview->isChecked() );
	config->writeEntry( "storeth", storeth );
	config->writeEntry( "storeth", imageList->il->getStoreThumbnails() );
	config->writeEntry( "showFrame", showFrame );
	config->writeEntry( "showhiddenDir", dirView->showHiddenDir() );
	config->writeEntry( "showhiddenFile", dirView->showHiddenFile() );
	config->writeEntry( "showDir", dirView->showDir() );
	config->writeEntry( "showallFile", dirView->showAllFile() );
	config->writeEntry( "loadFirstImage", dirView->loadFirstImage() );

	config->writeEntry( "preloadIm", imageList->preloadIm());
	config->writeEntry( "showMeta", imageList->showMeta());
	config->writeEntry( "showHexa", imageList->showHexa());

	config->writeEntry("WordWrapIconText", imageList->wordWrapIconText());
	config->writeEntry("ShowMimeType", imageList->getShowMimeType());
	config->writeEntry("ShowSize", imageList->getShowSize());
	config->writeEntry("ShowDate", imageList->getShowDate());
	config->writeEntry("ShowDimension", imageList->getShowDimension());
	config->writeEntry("ShowToolTips", imageList->getShowToolTips());

	config->setGroup("Slideshow");
	config->writeEntry( "time", slideshowTime );
	config->writeEntry( "type", slideshowType );
	config->writeEntry( "loop", imageList->doLoop() );	
		
	config->setGroup("confirm");
	config->writeEntry( "openDirType", openDirType );
	if(openDirType==1) openDirname=currentDir();
	config->writePathEntry( "openDirname",  openDirname);
	config->writeEntry( "showSP",  showSP);
	config->writeEntry( "startFS",  startFS);
	config->writeEntry( "useEXIF",  iv->useEXIF());

	config->writeEntry( "showToolbar",  showToolbar);
	config->writeEntry( "showStatusbar",  showStatusbar);

	config->setGroup("Paths");
	config->writeEntry( "cdromPath", getcdromPath() );
	config->writeEntry( "gimpPath", imageList->getgimpPath() );
	config->writeEntry( "convertPath", convertPath );
	config->writeEntry( "jpegtranPath", jpegtranPath );

	KMainWindow::saveMainWindowSettings(config, "MainWindow");
	saveWindowSize(config);

	config->sync();
}

bool
MainWindow::preview()
{
	return aPreview->isChecked();
}


QString
MainWindow::getFileName(QString *fullName)
{
		int debut = fullName->findRev ("/");
		int fin = fullName->findRev (".");
		return fullName->mid(debut+1, fin-debut-1);
}


QString
MainWindow::getFileExt(QString *fullName)
{
		int pos = fullName->findRev (".");
		return  fullName->right (fullName->length () - pos-1);
}

QString
MainWindow::getFullName(QString *fullName)
{
		int pos = fullName->findRev ("/");
		return fullName->right (fullName->length () - pos-1);
}

QString
MainWindow::getFullPath(QString *fullName)
{
		int pos = fullName->findRev ("/");
		return fullName->left(pos+1);
}


DirectoryView*
MainWindow::getDirectoryView()
{
	return dirView;
}


void
MainWindow::convert()
{
	QPtrList <QString> list;
	list.setAutoDelete (FALSE);

	for (FileIconItem * item = imageList->firstItem ();
	     item != 0;
	     item = item->nextItem ())
	{
		if (item->isSelected () && item->isImage())
	        {
			list.append(new QString(item->fullName()));
		}
	}
	if(list.isEmpty())
	{
		KMessageBox::error(this, i18n("You have to select at least one file."));
		return;
	}
	////////////
	if(!formatConver) formatConver = new FormatConversion(this);
	formatConver->setCaption(i18n("Format Conversion of One Image","Format Conversion of %n Images",list.count()));
	switch(formatConver->exec())
	{
		case KDialogBase::Accepted :
			break;
		default : return;
	}
	setMessage(i18n("Conversion in progress..."));

	QString ext=formatConver->getType();
	QString opt=formatConver->getOptions();
	bool replace = formatConver->replace();

	stopWatchDir();
	if(preview())imageList->stopLoading();

	KProgressDialog *progres =  new KProgressDialog (this, "Conversion",
				i18n("Image conversion"),
				QString::null,
				true);
	progres->progressBar()->setTotalSteps(list.count()+1);
	progres->adjustSize();
	progres->show();

	QString *name;
	int done=0;
	KShellProcess* proc = new KShellProcess ();
	//connect(proc, SIGNAL(processExited(KProcess *)), this, SLOT(slotEndConvert(KProcess *)));

	QString  msg, com;

	for ( name=list.first(); name != 0; name=list.next() )
	{
		msg = "<qt>"
			+i18n("Conversion of <b>%1</b>\n(%2/%3)")
				.arg(*name)
				.arg(done)
				.arg(list.count())
			+"</qt>";
		done++;
		//
		if ( progres->wasCancelled() ) break;
		progres->setLabel(msg);
		progres->progressBar()->setProgress(done);
		progres->repaint();kapp->processEvents();
		//
		proc->clearArguments();
		com = QString("convert %1 '%2' '%3'")
		  	     .arg(opt)
			     .arg(*name)
			     .arg(getFullPath(name)+getFileName(name)+"."+ext);
		*proc << com;
		proc->start (KShellProcess::Block);

		if(replace && ext!=getFileExt(name))
		{
			FileIconItem *item=imageList->findItem(getFileName(name));
			if(item) item->suppression();
		}
	}
	delete(progres);
	delete(proc);
	setMessage(i18n("Conversion done"));
	if(preview())imageList->slotLoadFirst();
	startWatchDir();
	slotRefresh ();
}

void
MainWindow::slotEndConvert(KProcess *proc)
{
	if(proc->exitStatus()!=0)
	{
		//qWarning(i18n("ERROR: during the conversion"));
	}

}

/////////////////////////////////////////////
char
MainWindow::getRed(QImage* im, int x, int y)
{
	return qRed(im->pixel(x, y));
}
char
MainWindow::getGreen(QImage* im, int x, int y)
{
	return qGreen(im->pixel(x, y));
}
char
MainWindow::getBlue(QImage* im, int x, int y)
{
	return qBlue(im->pixel(x, y));
}

ImageSimilarityData*
MainWindow::image_sim_fill_data(const QString& filename)
{
	int w, h;
	uchar *pix;
	int has_alpha;
	int p_step;

	int i,j;
	int x_inc, y_inc;
	int xs, ys;
	const int INC=1;

	QImage *pixbuf;
	ImageSimilarityData *sd = new ImageSimilarityData();
	sd->filename=filename;

	QFileInfo info(QDir::homeDirPath()+"/.showimg/cache/" + QFileInfo(filename).absFilePath()+".dat");
	if(info.exists())
	{
		QFile f(QDir::homeDirPath () + "/.showimg/cache/"+QFileInfo(filename).absFilePath()+".dat");
		if ( f.open(IO_ReadOnly) )
		{
			QDataStream s( &f );
			s >> sd->ratio;
			for(int i=0;i<PAS*PAS;i++) s >> sd->avg_r[i];
			for(int i=0;i<PAS*PAS;i++) s >> sd->avg_g[i];
			for(int i=0;i<PAS*PAS;i++) s >> sd->avg_b[i];
			f.close();
		}
		sd->filled = TRUE;
		return sd;
	}

	pixbuf = new QImage(filename);
	if (!sd || !pixbuf) return 0L;
	KImageEffect::equalize(*pixbuf);

	w = pixbuf->width();
	h = pixbuf->height();
	pix = pixbuf->bits();
	has_alpha = pixbuf->hasAlphaBuffer();
	p_step = has_alpha ? 4 : 3;

	x_inc = w / PAS;
	y_inc = h / PAS;
	if (x_inc < 1 || y_inc < 1) return 0L;

	j = 0;
	for (ys = 0; ys < PAS; ys++)
	{
		i = 0;
		for (xs = 0; xs < PAS; xs++)
		{
			int x, y;
			int r, g, b;
			r = g = b = 0;
			for (y = j; y < j + y_inc; y+=INC)
			{
				for (x = i; x < i + x_inc; x+=INC)
				{
					r +=getRed(pixbuf, x, y);
					g +=getGreen(pixbuf, x, y);
					b +=getBlue(pixbuf, x, y);
				}
			}
			r /= x_inc * y_inc;
			g /= x_inc * y_inc;
			b /= x_inc * y_inc;

			sd->avg_r[ys * PAS + xs] = r;
			sd->avg_g[ys * PAS + xs] = g;
			sd->avg_b[ys * PAS + xs] = b;

			i += x_inc;
		}
		j += y_inc;
	}
	sd->filled = TRUE;
	sd->ratio=((float)w)/h;
	delete(pixbuf);

	//////////////////////SAUVEGARDE//////////////
	QFile f(QDir::homeDirPath () + "/.showimg/cache/"+QFileInfo(filename).absFilePath()+".dat");
	KStandardDirs::makeDir(QFileInfo(f).dirPath(TRUE));
	if ( f.open(IO_WriteOnly) )
	{
		QDataStream s( &f );
		s << sd->ratio;
		for(int i=0;i<PAS*PAS;i++) s << sd->avg_r[i];
		for(int i=0;i<PAS*PAS;i++) s << sd->avg_g[i];
		for(int i=0;i<PAS*PAS;i++) s << sd->avg_b[i];
		f.close();
	}
	return sd;
}

float
MainWindow::image_sim_compare(ImageSimilarityData *a, ImageSimilarityData *b)
{
	float sim;
	int i;

	if (!a || !b || !a->filled || !b->filled) return 0.0;
	sim = 0.0;
	for (i = 0; i < PAS*PAS; i++)
	{
		sim += (float)abs(a->avg_r[i] - b->avg_r[i]) / 255.0;
		sim += (float)abs(a->avg_g[i] - b->avg_g[i]) / 255.0;
		sim += (float)abs(a->avg_b[i] - b->avg_b[i]) / 255.0;
	}
	sim /= (1024.0 * 3.0);
	return 1.0 - sim;
}

float
MainWindow::image_sim_compare_fast(ImageSimilarityData *a, ImageSimilarityData *b, float min)
{
	float sim;
	int i,j;

	if (!a || !b || !a->filled || !b->filled) return 0.0;

	if( fabs(a->ratio - b->ratio) > 0.1 ) return 0.0;
	min = 1.0 - min;
	sim = 0.0;

	for (j = 0; j < PAS*PAS; j+= PAS)
	{
		for (i = j; i < j + PAS; i++)
		{
			sim += (float)abs(a->avg_r[i] - b->avg_r[i]) / 255.0;
			sim += (float)abs(a->avg_g[i] - b->avg_g[i]) / 255.0;
			sim += (float)abs(a->avg_b[i] - b->avg_b[i]) / 255.0;
		}
		/* check for abort, if so return 0.0 */
		if (j>PAS*PAS/3 && 1-sim/((j+1) * 3.0) <min)
		{
			return 0.0;
		}
	}
	sim /= (PAS*PAS * 3.0);

	return 1.0 - sim;
}

void
MainWindow::compareAlmost ()
{
	setMessage(i18n("Comparisons in progress..."));
	KProgressDialog *progres =  new KProgressDialog (this, "Comparisons",
				i18n("Image Comparisons"),
				QString::null,
				true);

	QDict < QPtrVector < QFile > >*res = new QDict < QPtrVector < QFile > >;

	QPtrVector < ImageSimilarityData > *listRatW = new QPtrVector < ImageSimilarityData >;
	QPtrVector < ImageSimilarityData > *listRatH = new QPtrVector < ImageSimilarityData >;
	QPtrVector < ImageSimilarityData > *list;
	listRatW->setAutoDelete(TRUE);
	listRatH->setAutoDelete(TRUE);

	///////////////
	progres->setLabel(i18n("Create matrix for:"));
	progres->adjustSize();

	FileIconItem *item = imageList->firstItem ();
	int total=0;
	while (item){item = item->nextItem();total++;}
	progres->progressBar()->setTotalSteps(total);
	progres->adjustSize();
	progres->show();

	QTime debut=QTime::currentTime ();
	int current=0;
	ImageSimilarityData *is;
	item = imageList->firstItem ();
	while (item)
	{
		if(!item->isImage()) {item = item->nextItem (); continue;}

		progres->setLabel(
			"<qt>"
			+i18n("Create matrix for:<center>%1</center>").arg(item->fullName())
			+"</qt>");
		if ( progres->wasCancelled() )
		{
			delete (progres);
			delete(res);
			setMessage(i18n("Ready"));
			return;
		}
		progres->progressBar()->setProgress (++current);
		// file creation
		// file added
		if( (is=image_sim_fill_data(item->fullName()))!=NULL )
		{
			if(is->ratio>1)
				list = listRatW;
			else
				list = listRatH;
			list->resize (list->size () + 1);
			list->insert (list->size () - 1, is );
		}
		//we compuate the next one
		item = item->nextItem ();
	}
	MYDEBUG << "Time of the creation of matrices is  " << debut.msecsTo(QTime::currentTime()) << endl;
	debut=QTime::currentTime ();

	//////////////
	total=0;
	progres->progressBar()->setProgress(total);
	///////////////The files are compare
	QDict < QFile > *fait = new QDict < QFile >;
	list = listRatW;
	bool done=FALSE;
	while(list!=NULL)
	{
		if (list->size () != 1)
		{
			progres->setLabel(i18n("Approximate comparison in progress..."));
			for (unsigned int i = 0; i < list->size (); i++)
			{
				////////PROGRESSBAR MANAGEMENT//////////
				progres->progressBar()->setProgress (++total);
				kapp->processEvents();
				if ( progres->wasCancelled() )
				{
					done=TRUE;
					break;
				}
				/////CREATION of ImageSimilarityData of the first image////////
				ImageSimilarityData *i1 = list->at(i);
				if (i1 && !fait->find(i1->filename))
				{
					for (unsigned int j = i + 1; j < list->size (); j++)
					{
						/////CREATION of ImageSimilarityData os the seconde image////////
						ImageSimilarityData *i2 = list->at(j);

						///////COMPARAISON DES IMAGES ////////////
						float eq = image_sim_compare_fast(i1, i2, (float)0.88);
						if (eq>=0.88)   //files are the same
						{
							QPtrVector < QFile > *vect;
							 //they are added in the file
							if (!res->find (i1->filename))
							{
								vect = new QPtrVector < QFile >;
								vect->setAutoDelete(TRUE);
								res->insert (i1->filename, vect);
		        				}
		        				else
		        				{
		        					vect = (QPtrVector < QFile > *)res->find(i1->filename);
		        				}
		        				vect->resize (vect->size () + 1);
		        				vect->insert (vect->size () - 1, new QFile(i2->filename));
							fait->insert(i2->filename, new QFile(i2->filename));
						}
					}
				}
			}
		}
		if(!done)
		{
			list = listRatH;
			done=TRUE;
		}
		else
			list=NULL;
	}
	delete(fait);
	delete (progres);
	MYDEBUG << "Time of the cmp is " << debut.msecsTo(QTime::currentTime()) << endl;
	///////end/////////
	setMessage(i18n("Ready"));
	if(!res->isEmpty())
	{
		DisplayCompare(this, res).exec();
	}
	else
	{
		KMessageBox::information(this, i18n("No similar files found."));
	}

	delete(res);
	delete(listRatH);delete(listRatW);
}


void
MainWindow::compareFast ()
{
	setMessage(i18n("Fast comparisons in progress..."));
	KProgressDialog *progres =  new KProgressDialog (this, "Comparisons",
				i18n("Image Comparisons"),
				QString::null,
				true);
	progres->setLabel(i18n("Comparison in progress..."));
	progres->show();

	QDict < QPtrVector < QFile > >*dict = new QDict < QPtrVector < QFile > >;
	dict->setAutoDelete(TRUE);
	QDict < QPtrVector < QFile > >*res = new QDict < QPtrVector < QFile > >;
	QPtrVector < QFile > *list;
	long total = 0;

	QString size;
	QFile *file;
	int nbrF=0;

	FileIconItem *item = imageList->firstItem();
	while (item)
	{
		if(!item->isImage())  {item = item->nextItem (); continue;}
		nbrF++;

		//creation d un file
		file = new QFile (item->fullName ());
		//on recupere la taille sous forme de chaine
		size = QString::number (QFileInfo (*file).size ());
		//si pas dans la table, on creer
		if (!dict->find (size))
		{
			list = new QPtrVector < QFile >;
			list->setAutoDelete(TRUE);
			dict->insert (size, list);
		}
		//on recupere la liste
		list = (QPtrVector < QFile > *)dict->find (size);
		//on ajoute le file
		list->resize (list->size () + 1);
		list->insert (list->size () - 1, file);
		//on passe au suivant
		item = item->nextItem ();
	}

	/////////////
	//comparaison des fichiers
	QDictIterator < QPtrVector < QFile > >it (*dict);        // iterator for dict
	while (it.current ())
	{
		QDict < QFile > *fait = new QDict < QFile >;
		list = (QPtrVector < QFile > *)it.current ();
		if ( progres->wasCancelled() )
			break;
		progres->progressBar()->setProgress (total += list->size ());
		if ( progres->wasCancelled() )
		{
			delete (it);
			delete (progres);
			delete (res);
			KApplication::restoreOverrideCursor ();
			return;
		}
		if (list->size () != 1)
		{
			for (unsigned int i = 0; i < list->size (); i++)
			{
				QFile *file1 = (QFile *) (list->at (i));
				if (!fait->find (file1->name()))
				{
					for (unsigned int j = i + 1; j < list->size (); j++)
					{
						QFile *file2 = (QFile *) (list->at (j));
						if (equals (file1, file2))	  //les fic sont egaux
						{
							QPtrVector < QFile > *vect;
							//on ajoute le file
							if (!res->find (file1->name ()))
							{
								vect = new QPtrVector < QFile >;
								vect->setAutoDelete(TRUE);
								res->insert (file1->name (), vect);
							}
							else
							{
								vect = (QPtrVector < QFile > *)res->find (file1->name ());
							}
							vect->resize (vect->size () + 1);
							vect->insert (vect->size () - 1, file2);

							fait->insert(file2->name(), file2);
						}
					}
				}
			}
		}
		delete(fait);
		++it;
	}

	delete (it);
	delete (progres);
	setMessage(i18n("Ready"));
	if(!res->isEmpty())
	{
		DisplayCompare(this, res).exec();
	}
	else
	{
		KMessageBox::information(this, i18n("No identical files found."));
	}
	delete(res);
}


bool
MainWindow::equals (QFile * f1, QFile * f2)
{
	if (QFileInfo (*f1).size () != QFileInfo (*f2).size ())
	{
		return FALSE;
	}

	f1->open (IO_ReadOnly);
	f2->open (IO_ReadOnly);

	QDataStream s1 (f1);
	QDataStream s2 (f2);

	Q_INT8 b1, b2;
	bool eq = TRUE;

	while (!s1.atEnd () && eq)
	{
		s1 >> b1;
		s2 >> b2;

		eq = (b1 == b2);
	}

	f1->close ();
	f2->close ();

	return eq;
}

void
MainWindow::slotScanned( const QImage& img, int )
{
	if(lastDestDir.isEmpty())lastDestDir=currentDir();
	QString url=KFileDialog::getSaveFileName(lastDestDir,
						"*.png *.jpg *.gif *.bmp",
						iv,
						i18n("Save file as..."));
	if(!url.isEmpty())
	{
		lastDestDir = url;
		QString ext=QFileInfo(lastDestDir).extension().upper();
		if(ext.isEmpty())
		{
			lastDestDir+=".png";
			ext="PNG";
		}
		else
		if(ext=="JPG")
		{
			ext="JPEG";
		}
		if(! img.save(lastDestDir, ext.local8Bit(), 100) )
			KMessageBox::error(this, i18n("Error saving image."));
	}
}

void
MainWindow::slotScanImage()
{
#ifndef SHOWIMG_NO_SCAN_IMAGE
	KApplication::setOverrideCursor (waitCursor);

	if ( !m_scanDialog )
	{
		m_scanDialog = KScanDialog::getScanDialog( this, "scandialog" );
		if ( !m_scanDialog ) // no scanning support installed?
		{
			KApplication::restoreOverrideCursor ();
			KMessageBox::error(this, i18n("Error while initialising scanning (no scanning support installed?)"));
			return;
		}

		connect( m_scanDialog, SIGNAL( finalImage( const QImage&, int )),
			SLOT( slotScanned( const QImage&, int ) ));
	}

	if ( m_scanDialog->setup() ) // only if scanner configured/available
		m_scanDialog->show();

	KApplication::restoreOverrideCursor ();
#endif
}
/*
char MainWindow::getRed(QImage* , int , int ){return 0;}
char MainWindow::getGreen(QImage* , int , int ){return 0;}
char MainWindow::getBlue(QImage* , int , int ){return 0;}
ImageSimilarityData* MainWindow::image_sim_fill_data(QString ){return NULL;}
float MainWindow::image_sim_compare(ImageSimilarityData *, ImageSimilarityData *){return -1;}
float MainWindow::image_sim_compare_fast(ImageSimilarityData *, ImageSimilarityData *, float ){return -1;}
void MainWindow::compareAlmost (){}
void MainWindow::compareFast (){}
bool MainWindow::equals (QFile *, QFile *){return FALSE;}
void MainWindow::slotScanned( const QImage& , int ){};
void MainWindow::slotScanImage(){}
*/



ListItem*
MainWindow::findDir(QString dir)
{
	if(QFileInfo(dir).isDir()&&!dir.endsWith("/")) dir+="/";
	return dirView->getDir(dir);
}


bool
MainWindow::openDir (const QString& dir, bool updateHistory_)
{
	QString picName;
	QString _dir_;
	
	if(dirView->isImage(dir))
	{
		picName=QFileInfo(dir).fileName();
		_dir_=QFileInfo(dir).dirPath(TRUE);
	}
	else
	{
		_dir_=dir;
	}

	ListItem *ssrep = NULL;
	ListItem *f_ssrep = NULL;
	QFileInfo info( _dir_ );
	QStringList list = QStringList::split('/', info.absFilePath() );
	if(info.exists()
#ifndef SHOWIMG_NO_CDARCHIVE
		&& !_dir_.startsWith(CDArchive_ROOTPATH) 
		&& !_dir_.startsWith(CDArchive::CDArchive_TEMP_ROOTPATH()) 
#endif
	)
	{
		ssrep = root;

		QStringList::iterator it;
		for ( it = list.begin(); it != list.end(); ++it )
		{
			f_ssrep = ssrep->find ( *it );
			if ( ! f_ssrep )
				f_ssrep = new Directory((Directory*)ssrep, *it, dirView, iv, imageList, this);
			ssrep = f_ssrep;
			ssrep->setOpen(TRUE);
		}
	}
	else
	{
#ifndef SHOWIMG_NO_CDARCHIVE
		if(_dir_.startsWith(CDArchive::CDArchive_TEMP_ROOTPATH()) || _dir_.startsWith(CDArchive_ROOTPATH))
		{
			ssrep = cdArchiveRoot->find(_dir_);
		}
#endif
		if(ssrep)
			ssrep->setOpen(TRUE);
	}

	if (ssrep)
	{
		if(info.absFilePath () != currentDir())
		{
			dirView->clearSelection();
			dirView->slotShowItem(ssrep);
			dirView->setCurrentItem (ssrep);
			dirView->setSelected (ssrep, TRUE);

			setCaption(_dir_);
			setCurrentDir(_dir_);
		}
		if(updateHistory_)
		{
			updateHistory();
		}
		if(!picName.isEmpty()) imageList->setCurrentItemName(picName);
		return TRUE;
	}
	else
	{
		KMessageBox::error(this, "<qt>"+i18n("Unable to open the directory <b>%1</b>").arg(dir)+"</qt>");
		return FALSE;
	}
}



void
MainWindow::nextDir (ListItem *r)
{
	if (r == 0)
	{
		return;
	}

	if(!r->fullName ())
	{
		return;
	}
	ListItem *dir = r;
	while (dir != 0)
	{
		if (dir->text (1) != i18n("Directory"))
		{
			dir = 0;
		}
		else
		{
			if (dir->isSelected ())
			{
				dir->unLoad ();
				dir->load ();
			}

			if (dir->firstChild ())
			{
				nextDir (dir->firstChild ());
			}
		}
		dir = dir->itemBelow ();
	}
}


void
MainWindow::renameSeries()
{
	KApplication::setOverrideCursor (waitCursor);

	if(!m_renameS)
	{
		m_renameS = new RenameSeries(this,"RenameSeries");
		m_renameS->readConfig(config, CONFIG_BATCHRENAME);
	}
	else
		m_renameS->clear();
	QString fullName, name;
	bool hasFiles=FALSE;
	for (FileIconItem * item = imageList->firstItem (); item != 0; item = item->nextItem ())
	{
		if (item->isSelected () )
		{
			m_renameS->addFile(item->fullName());
			hasFiles=TRUE;
		}
	}
	if(!hasFiles)
	{
		KApplication::restoreOverrideCursor ();
		KMessageBox::error(this, i18n("You have to select at least one file."));
		return;
	}
	KApplication::restoreOverrideCursor ();
	if(m_renameS->exec())
	{
		slotRefresh();
	}

}


void
MainWindow::slotRefresh (const QString& dir)
{
	setMessage(i18n("Refreshing..."));

	QString res = QString(dir);
	int  pos = res.find ("/");
	ListItem *ssrep;

	res = res.right (res.length () - pos - 1);
	pos = res.find ("/");

	ssrep = root;
	while (pos != -1)
	{
		ssrep = ssrep->find (res.left (pos));
		res = res.right (res.length () - pos - 1);

		if (ssrep)
			pos = res.find ("/");
		else
			break;
	}
	ssrep = ssrep->find (res);
	if (ssrep && ssrep->isSelected ())
	{
		ssrep->refresh();
	}

	setMessage(i18n("Ready"));
}


void
MainWindow::slotRefresh (bool forceRefresh)
{
	setMessage(i18n("Refreshing..."));
	imageList->stopLoading();

	QPtrList<ListItem> list;
	QListViewItemIterator it (root);
	for (; it.current (); ++it)
	{
		if (it.current ()->isSelected ())
			list.append((ListItem*)(it.current()));
	}
	for ( ListItem *dir=list.first(); dir != 0; dir=list.next() )
	{
		if(!forceRefresh)
		{
			dir->refresh(FALSE);
		}
		else
		{
			dir->unLoad();
			dir->load();
		}
	}
	imageList->reload();
	imageList->slotLoadFirst();
	setMessage(i18n("Ready"));
}



void
MainWindow::setHasImageSelected(bool selected)
{
	hasimageselected=selected;

#ifndef HAVE_KIPI
	aWallpaper_CENTER->setEnabled(selected);
	aWallpaper_MOSAIC->setEnabled(selected);
	aWallpaper_CENTER_MOSAIC->setEnabled(selected);
	aWallpaper_CENTER_MAX->setEnabled(selected);
	aWallpaper_ADAPT->setEnabled(selected);
	aWallpaper_LOGO->setEnabled(selected);
#endif /* HAVE_KIPI */

	//aCut->setEnabled(selected);
	aCopy->setEnabled(selected);
	aCopyPixmap->setEnabled(selected);
	aRename->setEnabled(selected);
	aDelete	->setEnabled(selected);
	aTrash	->setEnabled(selected);
	aShred	->setEnabled(selected);
	aEditType->setEnabled(selected);
	aFileProperties->setEnabled(selected);
	aImageInfo->setEnabled(selected);

	aFullScreen->setEnabled(selected);

	iv->selectionChanged(selected);

	aOpenWithGimp->setEnabled(selected);
	aOpenWith->setEnabled(selected);
	aSaveImage->setEnabled(selected);
	aFilesMoveTo->setEnabled(selected);
	aFilesCopyTo->setEnabled(selected);

	FileIconItem* si = imageList->firstSelected();
	if(si)
	{
		if(si->getType() != "file" && si->getType() != "dir")
		{
			aPaste->setEnabled(FALSE);
			aRename->setEnabled(FALSE);
			aTrash	->setEnabled(FALSE);
			aImageInfo->setEnabled(FALSE);
			aFilesMoveTo->setEnabled(FALSE);

				//
			if(si->getType()=="filealbum")
			{
				m_actions->action("editdelete")->setText(i18n("Remove From Album"));
			}
			else
			if(si->getType()=="zip")
			{
				m_actions->action("editdelete")->setText(i18n("Remove From Archive"));
			}
			else
			{
				m_actions->action("editdelete")->setEnabled(FALSE);
			}
		}
		else
		{
			m_actions->action("editdelete")->setText(i18n("Delete File"));
		}
		if(!imageList->hasOnlyOneImageSelected())
		{
			aRename->setEnabled(FALSE);
			aImageInfo->setEnabled(FALSE);
			aEditType->setEnabled(FALSE);
			#ifdef HAVE_LIBKEXIF
			aDisplayExifInformation->setEnabled(FALSE);
			#endif
			m_actions->action("EXIF orientation")->setEnabled(FALSE);
		}
		#ifdef HAVE_LIBKEXIF
		else
		{
			aDisplayExifInformation->setEnabled(si->mimetype()=="image/jpeg");
			
			m_actions->action("EXIF actions")->setEnabled(si->mimetype()=="image/jpeg");
			m_actions->action("EXIF orientation")->setEnabled(si->mimetype()=="image/jpeg");
		}
		#endif
	}
}


void
MainWindow::slotPreview ()
{
	slotIconSize(FALSE);
	if(aPreview->isChecked())
	{
		imageList->slotLoadFirst();
		
		m_actions->action("Regenerate EXIF thumbnail")->setEnabled(true);
		m_actions->action("Regenerate thumbnail")->setEnabled(true);
	}
	else
	{
		slotStop();
		imageList->slotResetThumbnail();
		
		m_actions->action("Regenerate EXIF thumbnail")->setEnabled(false);
		m_actions->action("Regenerate thumbnail")->setEnabled(false);
	}
}


void
MainWindow::slotSlideShow ()
{
#ifdef HAVE_KIPI
	if (pluginManager_->action("SlideShow...") && aSlideshow->isChecked())
	{
		pluginManager_->action("SlideShow...")->activate();
		aSlideshow->setChecked(false);
		return;
	}
#endif /* HAVE_KIPI */
	if (!timer->isActive())
	{
		KApplication::setOverrideCursor (KCursor:: blankCursor()); // this might take time
		timer->start (slideshowTime*1000, FALSE);
		if(!inFullScreen) slotFullScreen();
	}
	else
		timer->stop ();
}


void
MainWindow::escapePressed()
{
	if(fullScreen())
	{
		if(!inInterface)
			queryClose();
		else
			slotFullScreen();
	}
	else
	{
		slotStop();
	}
}
void
MainWindow::spacePressed()
{
	if(fullScreen())
	{
		if(!iv->scrollDown ())
			imageList->next();
	}
}

void
MainWindow::slotFullScreen()
{
	if(! iv->hasImage())
		return;
	hide();
	setUpdatesEnabled(FALSE);

	if (!inFullScreen )
	{
		imageList->inFullScreen = TRUE;
		inFullScreen = TRUE;
		inInterface=TRUE;

		writeDockConfig (config, CONFIG_DOCK_GROUP);

		makeDockInvisible(dockIL);
		makeDockInvisible(dockDir);
		makeDockInvisible(dockIMI);

		toolBar("locationToolBar")->hide();
		menuBar()->hide();
		if(!showToolbar)
		{
			toolBar("mainToolBar")->hide();
			toolBar("viewToolBar")->hide();
			topDock()->hide();
		}
		if(!showStatusbar)
		{
			statusBar()->hide();
			bottomDock()->hide();
		}

		aBack->setEnabled(FALSE);aForward->setEnabled(FALSE);
		aGoHome->setEnabled(FALSE);aGoUp->setEnabled(FALSE);
		aGo->setEnabled(false);
		aPreview->setEnabled(FALSE);

		iv->setBackgroundColor(QColor("black"));

		showFullScreen();
		iv->setFocus();
	}
	else
	{
		inFullScreen = FALSE;
		imageList->inFullScreen = FALSE;
		readDockConfig (config, CONFIG_DOCK_GROUP);

		iv->setBackgroundColor(bgColor);

		topDock()->show();
		bottomDock()->show();

		menuBar()->show();

		aBack->setEnabled(TRUE);aPrevious->setEnabled(TRUE);
		aGoHome->setEnabled(TRUE);aGoUp->setEnabled(TRUE);
		aGo->setEnabled(true);
		aPreview->setEnabled(TRUE);

		menuBar()->show();

		aBack->setEnabled(TRUE);aPrevious->setEnabled(TRUE);
		aGoHome->setEnabled(TRUE);aGo->setEnabled(true);
		aGoUp->setEnabled(TRUE);

		toolBar("mainToolBar")->show();
		toolBar("viewToolBar")->show();
		toolBar("locationToolBar")->show();
		statusBar()->show();

		if(timer->isActive()) {timer->stop(); aSlideshow->setChecked(FALSE); KApplication::restoreOverrideCursor ();}

		showNormal();
	}
	aFullScreen->setChecked(inFullScreen);
	setUpdatesEnabled(TRUE);
	show();
}


void
MainWindow::closeEvent( QCloseEvent* e)
{
	KDockMainWindow::closeEvent(e);
}

bool
MainWindow::closeAppl()
{
	return TRUE;
}

bool
MainWindow::queryClose()
{
	if(deleteTempDirectoriesDone_)
	{
		if(inFullScreen)
		slotFullScreen();
		writeConfig(config);
		iv->writeConfig(config, CONFIG_IMAGEVIEWER_GROUP);
		if(m_renameS) m_renameS->writeConfig(config, CONFIG_BATCHRENAME);
		writeDockConfig(config, CONFIG_DOCK_GROUP);
		config->sync();
		return TRUE;
	}
	else
	{
		deleteTempDirectories();
		return false;
	}
}


void
MainWindow::slotAddImage (int number)
{
	total+=number;
	setNbrItems(total);
	progress->setTotalSteps (total);
}

void
MainWindow::slotRemoveImage ()
{
	total--;setNbrItems(total);
	progress->setTotalSteps (total);
}

void
MainWindow::slotPreviewDone (int number)
{
	done+=number;
	progress->setProgress (done);
}

void
MainWindow::slotReset (bool init)
{
	aStop->setEnabled(TRUE);
	if(init)
	{
		done = 0;
		progress->setProgress (-1);
	}
	if(total>=1) progress->show();
}

void
MainWindow::slotDone()
{
	aStop->setEnabled(FALSE);
	done = total;
	progress->hide();
	
	if(aPreview->isChecked())
	{
		m_actions->action("Regenerate thumbnail")->setEnabled(true);
		m_actions->action("Regenerate EXIF thumbnail")->setEnabled(true);
	}
}

void
MainWindow::slotRemoveImage (int val)
{
	total -= val;setNbrItems(total);
	progress->setTotalSteps (total);
	progress->setProgress (total);
}


void
MainWindow::slotDirChange (const QString& path)
{
	if(QFileInfo(path).isDir())
	{
		ListItem* d = findDir(path);
		if(d)
		{
			if(d->refresh())
			{
				imageList->slotLoadFirst();
			}
		}
	}
}


void
MainWindow::slotDirChange_created(const QString& path)
{
}

void
MainWindow::slotDirChange_deleted(const QString& path)
{
	dirView->removeDir(path);
}


void
MainWindow::slotTODO ()
{
	KMessageBox::sorry(this,
		i18n("Not yet implemented.\nSorry ;("),
		i18n("Functionality"));
}

void
MainWindow::slotcopyPixmap()
{
	KApplication::setOverrideCursor (waitCursor); // this might take time
	KApplication::clipboard()->setPixmap(iv->getPixmap());
	KApplication::restoreOverrideCursor ();
}

void
MainWindow::slotcopy ()
{
	QString files, name;
	KURL::List list;

	for (FileIconItem* item = imageList->firstItem(); item != 0; item = item->nextItem())
	{
		if (item->isSelected () )
		{
			list.append(item->getURL());
		}
	}
	QClipboard *cb = KApplication::clipboard();
	cb->setData(new KURLDrag(list, this, "MainWindow"));
}


void
MainWindow::slotcut ()
{
	slotTODO ();
}

void
MainWindow::slotpaste ()
{
	KURL::List uris;
	if(KURLDrag::decode(KApplication::clipboard()->data(), uris))
	{
		if(!uris.isEmpty())
			dirView->copy(uris.toStringList(), currentTitle());
	}
}


void
MainWindow::slotNewWindow()
{
	(void)new MainWindow("new Main Frame", currentDir());
}


void
MainWindow::slotOpenLocation()
{
	QString destDir=KFileDialog::getExistingDirectory(currentDir(),
								this,
								i18n("Open Location"));

	if(!destDir.isEmpty())
	{
		if(!QFileInfo(destDir).exists())
		{
			KMessageBox::error(this, "<qt>"+i18n("The directory '<b>%1</b>' does not exist").arg(destDir)+"</qt>");
			return;
		}
		openDir(destDir);
		changeDirectory(destDir);
	}
}

void
MainWindow::slotSaveImage()
{
	if(lastDestDir.isEmpty())lastDestDir=currentDir();
	lastDestDir=iv->slotSave(lastDestDir);
}

void
MainWindow::slotUndo()
{
	slotTODO ();
}


void
MainWindow::slotRedo()
{
	slotTODO ();
}



void
MainWindow::slotEditFileType()
{
	if(!imageList->currentItem())
		return;
#ifndef Q_WS_WIN
	KonqOperations::editMimeType( imageList->currentItem()->mimetype());
#endif
}


void
MainWindow::slotStop()
{
	imageList->stopLoading ();
	slotDone();
}




void
MainWindow::slotShowTips()
{
  KTipDialog::showTip( this, "showimg/tips", TRUE );
}


void
MainWindow::configureKey()
{
	KKeyDialog::configure(m_actions, this);
}


void
MainWindow::configureToolbars()
{
	saveMainWindowSettings( KGlobal::config(), "MainWindow" );
	KEditToolbar dlg(m_actions);
	if (dlg.exec())
	{
		createGUI();
		applyMainWindowSettings( KGlobal::config(), "MainWindow" );
	}

}


void
MainWindow::configureShowImg()
{
	ConfShowImg conf(this);
	conf.initColor(iv->bgColor(), iv->toGrayscale());
	conf.initFiling(openDirType, openDirname, showSP, startFS);
	conf.initMiscellaneous(iv->smooth(), dirView->loadFirstImage(), dirView->showHiddenDir(), dirView->showHiddenFile(), dirView->showDir(), dirView->showAllFile(), imageList->preloadIm());
	conf.initThumbnails(imageList->il->getStoreThumbnails(), showFrame, iv->useEXIF(), imageList->wordWrapIconText(), imageList->getShowMimeType(), imageList->getShowSize(), imageList->getShowDate(), imageList->getShowDimension());
	conf.initSlideshow(slideshowType, slideshowTime);
	conf.initFullscreen(showToolbar, showStatusbar);
	conf.initProperties(imageList->showMeta(), imageList->showHexa());
	conf.initPaths(getcdromPath(), imageList->getgimpPath(), convertPath, jpegtranPath);
	conf.initImagePosition(iv->getImagePosition());

	if(conf.exec())
	{
		openDirType=conf.getOpenDirType();
		openDirname=conf.getOpenDir();
		showSP=conf.checkshowSP();
		startFS=conf.checkstartFS();
		iv->setUseEXIF(conf.getUseEXIF());
		showToolbar=conf.getShowToolbar();
		showStatusbar=conf.getShowStatusbar();

		imageList->setShowMimeType(conf.getShowMimeType());
		imageList->setShowSize(conf.getShowSize());
		imageList->setShowDate(conf.getShowDate());
		imageList->setShowDimension(conf.getShowDimension());
		imageList->setWordWrapIconText(conf.getWordWrapIconText());

		dirView->setShowHiddenDir(conf.getShowHiddenDir());
		dirView->setShowHiddenFile(conf.getShowHiddenFile());
		dirView->setShowDir(conf.getShowDir());
		dirView->setLoadFirstImage(conf.getLoadFirstImage());
		dirView->setShowAllFile(conf.getShowAll());

		imageList->setPreloadIm(conf.getPreloadIm());
		imageList->setRandom(conf.getSlideshowType()==2);
		imageList->setShowMeta(conf.getShowMeta());
		imageList->setShowHexa(conf.getShowHexa());

		iv->setBackgroundColor(conf.getColor());
		iv->setToGrayscale(conf.getGrayscale());
		iv->setSmooth(conf.getSmooth());

		slideshowTime=conf.getSlideshowTime();
		slideshowType=conf.getSlideshowType();
		delete(timer); timer = new QTimer (this);
		if(slideshowType == 0 )
			connect (timer, SIGNAL (timeout ()), imageList, SLOT (next ()));
		else
			connect (timer, SIGNAL (timeout ()), imageList, SLOT (previous()));


		imageList->il->setStoreThumbnails(conf.getStoreth());
		showFrame=conf.getShowFrame();
		imageList->il->setShowFrame(showFrame);
		imageList->il->setUseEXIF(iv->useEXIF());

		setLayout(conf.getLayout());

#ifdef HAVE_KIPI
		conf.applyPlugins();
		pluginManager_->loadPlugins();
#endif /* HAVE_KIPI */

		imageList->selectionChanged();
		dirView->slotSelectionChanged();

		cdromPath = conf.getcdromPath();
		imageList->setgimpPath(conf.getgimpPath());
		convertPath = conf.getconvertPath();
		jpegtranPath = conf.getjpegtranPath();

		iv->setImagePosition(conf.getImagePosition());

		slotRefresh(TRUE);
	}
}

void
MainWindow::setLayout(int layout)
{
	switch(layout)
	{
		case 1:
				dockDir->manualDock(dockIV, KDockWidget::DockLeft, 35);
				dockIL->manualDock(dockDir, KDockWidget::DockBottom, 35);
				//aArrangementB->setChecked(TRUE);
				//aArrangementLR->setChecked(TRUE);
			break;
		case 2:
				dockDir->manualDock(dockIV, KDockWidget::DockTop, 35);
				dockIL->manualDock(dockDir, KDockWidget::DockRight, 50);
				//aArrangementB->setChecked(TRUE);
				//aArrangementLR->setChecked(TRUE);
			break;
		case 3:
				dockIL->manualDock(dockIV, KDockWidget::DockRight, 35);
				dockDir->manualDock(dockIV, KDockWidget::DockTop, 35);
				//aArrangementB->setChecked(TRUE);
				//aArrangementLR->setChecked(TRUE);
			break;
		case 4:
				dockDir->manualDock(dockIV, KDockWidget::DockLeft, 35);
				dockIL->manualDock(dockIV, KDockWidget::DockTop, 10);
				//aArrangementB->setChecked(TRUE);
				//aArrangementTB->setChecked(TRUE);
			break;
		default:
			return;
			break;
	}
}


//
/**
	bookmarkmanager
*/
void
MainWindow::openBookmarkURL(const QString& _url)
{
	KURL url(_url);
	QString path=url.url();
	url = KURL(path.replace("//", "/"));
	if(!url.isLocalFile())
	{
		KMessageBox::error(this, "<qt>"+i18n("The directory '<b>%1</b>' is not local").arg(url.url())+"</qt>");
		return;
	}
	else
	{
		if(!QFileInfo(url.path()).exists())
		{
			KMessageBox::error(this, "<qt>"+i18n("The directory '<b>%1</b>' does not exist").arg(url.url())+"</qt>");
			return;
		}
		openDir(url.path());
	}
}


QString
MainWindow::currentTitle() const
{
	return currentDir();
}


QString
MainWindow::currentURL() const
{
	return "file:"+currentDir();
}

/**
*/

//

void
MainWindow::addToBookmark(const QString& groupText, const QString& url)
{
	KBookmarkGroup root = MyBookmarkManager::self()->root();
	KBookmark bookm;
	bool bmAlbumExists = FALSE;
	for(bookm = root.first(); !bookm.isNull(); bookm = root.next(bookm))
	{
		if(bookm.text() == groupText)
		{
			bmAlbumExists=TRUE;
			break;
		}
	}
	KBookmarkGroup bmg;
	if(!bmAlbumExists)
	{
		bmg = MyBookmarkManager::self()->root().createNewFolder(MyBookmarkManager::self(), groupText);
		MyBookmarkManager::self()->root().moveItem(bmg, KBookmarkGroup());
	}
	else
	{
		bmg=bookm.toGroup();
	}
	bmg.addBookmark(MyBookmarkManager::self(), url, url, KMimeType::iconForURL(url));
	MyBookmarkManager::self()->emitChanged(root);
}


void
MainWindow::changeDirectory(QString dir)
{
	setCaption(dir);
	setCurrentDir(dir);
	updateHistory();
}


void
MainWindow::backMenuActivated(int item)
{
	go(-(aBack->popupMenu()->indexOf(item)+1));
}

void
MainWindow::slotBack()
{
	go(-1);
}

void
MainWindow::slotForward()
{
	go(+1);
}

void MainWindow::go( int steps )
{
	updateHistory();

	int newPos = m_lstHistory.at() + steps;
	HistoryEntry* l = m_lstHistory.at( newPos );
	if(openDir(l->filePath, FALSE))
	{
		aBack->setEnabled( m_lstHistory.at() > 0 );
		aForward->setEnabled( m_lstHistory.at() != ((int)m_lstHistory.count())-1 );
	}
}

void
MainWindow::updateHistory()
{
	KURL url;
	url.setPath(currentDir());
	///
	m_URLHistoryCompletion->addItem(url.prettyURL());
	m_URLHistory->setEditText(url.prettyURL());
	m_URLHistory->addToHistory(url.prettyURL());

	///
	HistoryEntry * current = m_lstHistory.current();
	HistoryEntry* newEntry = new HistoryEntry;
	newEntry->filePath = url.path();
	if (current && current->filePath == newEntry->filePath)
	{
		delete newEntry;
		return;
	}
	if (current)
	{
		m_lstHistory.at( m_lstHistory.count() - 1 ); // go to last one
		for ( ; m_lstHistory.current() != current ; )
		{
			m_lstHistory.removeLast();
		}
	}
	m_lstHistory.append(newEntry);
	aBack->setEnabled( m_lstHistory.at() > 0 );
	aForward->setEnabled( m_lstHistory.at() != ((int)m_lstHistory.count())-1 );
}



void
MainWindow::slotForwardAboutToShow()
{
	aForward->popupMenu()->clear();
	HistoryAction::fillHistoryPopup( m_lstHistory, aForward->popupMenu(), FALSE, TRUE );
}


void
MainWindow::slotBackAboutToShow()
{
	aBack->popupMenu()->clear();
	HistoryAction::fillHistoryPopup( m_lstHistory, aBack->popupMenu(), TRUE, FALSE );
}


/////////////
void
MainWindow::slotArrangement()
{
	if(aArrangementLR->isChecked())
		imageList->setArrangement(ImageListView::LeftToRight);
	else
		imageList->setArrangement(ImageListView::TopToBottom);
	slotIconSize(FALSE);
}

void
MainWindow::slotTxtPos()
{
	if(aArrangementR->isChecked())
		imageList->setItemTextPos(ImageListView::Right);
	else
		imageList->setItemTextPos(ImageListView::Bottom);
}


bool
MainWindow::fullScreen()
{
	return inFullScreen;
}

void
MainWindow::setEmptyImage()
{
	iv->loadImage();
}

void
MainWindow::copyFilesTo(const QStringList& uris, const QString& dest)
{
	dirView->copy(uris, dest);
}

void
MainWindow::moveFilesTo(const QStringList& uris, const QString& dest)
{
	dirView->move(uris, dest);
}


void
MainWindow::startWatchDir()
{
	dirView->startWatchDir();
}
void
MainWindow::stopWatchDir()
{
	dirView->stopWatchDir();
}



void
MainWindow::toolsRotateLeft()
{
	setMessage(i18n("Rotating..."));
	QPtrList <QString> list;
	list.setAutoDelete (TRUE);

	KURL::List listIm = imageList->selectedImageURLs();
	for(KURL::List::iterator it=listIm.begin(); it != listIm.end(); ++it)
		list.append(new QString((*it).path()));

	if(list.isEmpty())
	{
		KMessageBox::error(this, i18n("You have to select at least one file."));
	}
	else
	{
		stopWatchDir();
		imageList->stopLoading();

		KProgressDialog *progres =  new KProgressDialog (this, "Rotation",
				i18n("Image Rotation"),
				QString::null,
				true);
		progres->progressBar()->setTotalSteps(list.count()+1);
		progres->adjustSize();
		progres->show();

		int done=0;
		QString *name;

		KShellProcess* proc = new KShellProcess ();
		QString  msg, com;

		//
		bool HAVE_convert = !KStandardDirs::findExe(convertPath).isNull();
		bool HAVE_jpegtran = !KStandardDirs::findExe(jpegtranPath).isNull();

		//
		if(!HAVE_convert)
			KMessageBox::error(this, "<qt>"+i18n("You must install <tt>convert</tt> in order to manipulate images.")+"</qt>");
		else
		for ( name=list.first(); name != 0; name=list.next() )
		{
			if ( progres->wasCancelled() ) break;
			done++;
			//
			msg = "<qt>"
				+i18n("Rotating <center><b>%1</b><br>(%2/%3)</center>")
					.arg(*name)
					.arg(done)
					.arg(list.count())
				+"</qt>";
			progres->setLabel (msg);
			progres->progressBar()->setProgress (done);
			progress->repaint();kapp->processEvents();
			//
			QFileInfo finfo(*name);
			if(finfo.extension().lower() == "jpg" && HAVE_jpegtran)
			{
				QString dest = locateLocal("tmp", ".showimgtmppic%1%2")
					.arg(getpid())
					.arg(finfo.fileName());

				com = QString("jpegtran -rotate 270 -copy all -outfile");
				com += " " 		+ KProcess::quote(dest);
				com += " " 		+ KProcess::quote(*name);
				com += "&& mv -f " 	+ KProcess::quote(dest);
				com += " " 		+ KProcess::quote(*name);
			}
			else
			{
				com = QString("convert -rotate 270");
				com += " " + KProcess::quote(*name);
				com += " " + KProcess::quote(*name);
			}
			proc->clearArguments();
			*proc << com;
			proc->start (KShellProcess::Block);
			kapp->processEvents ();

			ImageLoader::rotateEXIFThumbnail(*name, ImageLoader::ROT_270);
			kapp->processEvents ();
		}
		delete(progres);
		delete(proc);
	}
	setMessage(i18n("Ready"));
	startWatchDir();
	slotRefresh();
}


void
MainWindow::toolsRotateRight()
{
	setMessage(i18n("Rotating..."));
	QPtrList <QString> list;
	list.setAutoDelete (TRUE);

	KURL::List listIm = imageList->selectedImageURLs();
	for(KURL::List::iterator it=listIm.begin(); it != listIm.end(); ++it)
		list.append(new QString((*it).path()));

	if(list.isEmpty())
	{
		KMessageBox::error(this, i18n("You have to select at least one file."));
	}
	else
	{
		stopWatchDir();
		imageList->stopLoading();

		KProgressDialog *progres =  new KProgressDialog (this, "Rotation",
				i18n("Image Rotation"),
				QString::null,
				true);
		progres->progressBar()->setTotalSteps(list.count()+1);
		progres->adjustSize();
		progres->show();

		int done=0;
		QString *name;

		KShellProcess* proc = new KShellProcess ();
		QString  msg, com;

		//
		bool HAVE_convert = !KStandardDirs::findExe("convert").isNull();
		bool HAVE_jpegtran = ! KStandardDirs::findExe("jpegtran").isNull();
		//
		if(!HAVE_convert)
			KMessageBox::error(this, "<qt>"+i18n("You must install <tt>convert</tt> in order to manipulate images.")+"</qt>");
		else
		for ( name=list.first(); name != 0; name=list.next() )
		{
			if ( progres->wasCancelled() ) break;
			done++;
			//
			msg = "<qt>"
				+i18n("Rotating <center><b>%1</b><br>(%2/%3)</center>")
					.arg(*name)
					.arg(done)
					.arg(list.count())
				+"</qt>";
			progres->setLabel (msg);
			progres->progressBar()->setProgress (done);
			progress->repaint();kapp->processEvents();
			//
			QFileInfo finfo(*name);
			if(finfo.extension().lower() == "jpg" && HAVE_jpegtran)
			{
				QString dest = locateLocal("tmp", ".showimgtmppic%1%2")
					.arg(getpid())
					.arg(finfo.fileName());

				com = QString("jpegtran -rotate 90 -copy all -outfile");
				com += " " 		+ KProcess::quote(dest);
				com += " " 		+ KProcess::quote(*name);
				com += "&& mv -f " 	+ KProcess::quote(dest);
				com += " " 		+ KProcess::quote(*name);
			}
			else
			{
				com = QString("convert -rotate 90");
				com += " " + KProcess::quote(*name);
				com += " " + KProcess::quote(*name);
			}
			proc->clearArguments();
			*proc << com;
			proc->start (KShellProcess::Block);
			kapp->processEvents ();

			ImageLoader::rotateEXIFThumbnail(*name, ImageLoader::ROT_90);
			kapp->processEvents ();
	}
	delete(progres);
	delete(proc);
	}
	setMessage(i18n("Ready"));
	startWatchDir();
	slotRefresh();
}

void
MainWindow::goHome()
{
	openDir(QDir::homeDirPath());
}

void
MainWindow::goUp()
{
	QDir dir(currentDir());dir.cdUp();
	openDir(dir.path());
}

void
MainWindow::clearCache()
{
	imageList->removeThumbnails(true);
}

void
MainWindow::clearCacheRec()
{
	clearCacheRec(currentDir());
}
void
MainWindow::clearCacheRec(const QString& fromDir)
{
#ifndef Q_WS_WIN
	KonqOperations::del(this, KonqOperations::DEL, imageList->il->clearThumbnailDir(fromDir));
#else
	(void)KIO::del(imageList->il->clearThumbnailDir(fromDir));
#endif
}

void
MainWindow::updateCache()
{
	KURL::List list = imageList->il->updateThumbnailDir(currentDir());

	pdCache=new KProgressDialog (this, "Thumbnail",
				i18n("Thumbnail progress"),
				QString::null,
				true);
	pdCache->setLabel(i18n("Updating in progress..."));
	pdCache->progressBar()->setTotalSteps(2);
	pdCache->progressBar()->setProgress(2);
	pdCache->show();
	pdCache->adjustSize();
	list += updateCache(currentDir());
	pdCache->close();
	delete(pdCache);

	//
#ifndef Q_WS_WIN
	KonqOperations::del(this, KonqOperations::DEL, list);
#else
	(void)KIO::del( list );
#endif
}

KURL::List
MainWindow::updateCache(const QString& fromDir)
{
	pdCache->setLabel(
		"<qt>"
		+i18n("Updating in progress for:<center>%1</center>")
			.arg(fromDir)
		+"</qt>"
		);
	kapp->processEvents();

	QDir d(QDir::homeDirPath()+"/.showimg/cache/"+fromDir);
	d.setFilter( QDir::All | QDir::Hidden | QDir::NoSymLinks );
	const QFileInfoList *dlist = d.entryInfoList();

	if(!dlist) return KURL::List();

	int len=QString(QDir::homeDirPath()+"/.showimg/cache").length();
	KURL::List list;
	QFileInfoListIterator it( *dlist );
	QFileInfo *fi;
	KURL m_url;
	while ( (fi = it.current()) != 0 )
	{
		QString fCache=fi->absFilePath();
		QString orgFile=fCache.right(fCache.length()-len);
		if(fi->isDir() && !fromDir.startsWith(orgFile))
		{
			list += updateCache(orgFile);
		}
		else
		{
			if(!QFileInfo(orgFile).exists() && QFileInfo(orgFile).extension(FALSE)!="dat")
			{
				m_url.setPath(fCache);
				list.append(m_url);

				m_url.setPath(fCache+".dat");
				list.append(m_url);

			}
		}
		++it;
	}
	return list;

}

void
MainWindow::slotDisplayNBImg()
{
	aTime->setText(i18n("%1 images seen").arg(iv->nbImg));
	KMessageBox::information(this, "<qt>"+i18n("You have already seen <b>%1</b> images.").arg(iv->nbImg)+"</qt>");
}

void
MainWindow::setCurrentDir(const QString& dir)
{
	currentDir_ = dir;
	if(QFileInfo(currentDir_).isDir() && !currentDir_.endsWith("/"))
			currentDir_+="/";

}

QString
MainWindow::currentDir() const
{
	return currentDir_;
}

QString
MainWindow::getcdromPath()
{
	return cdromPath;
}

#ifdef HAVE_KIPI
KIPIPluginManager*
MainWindow::pluginManager()
{
	return pluginManager_;
}
#endif /*HAVE_KIPI*/

void
MainWindow::deleteTempDirectories()
{
    hide();

    KURL::List list;
    KURL url;

    if(KStandardDirs::exists(locateLocal("tmp", "showimg-cpr/")))
    {
    	url.setPath(locateLocal("tmp", "showimg-cpr/"));
    	list.append(url);
    }
    if(KStandardDirs::exists(locateLocal("tmp", "showimg-arc/")))
    {
	    url.setPath(locateLocal("tmp", "showimg-arc/"));
	    list.append(url);
    }
    if(KStandardDirs::exists(locateLocal("tmp", "showimg-net/")))
    {
	    url.setPath(locateLocal("tmp", "showimg-net/") );
	    list.append(url);
    }
    KIO::DeleteJob *job = KIO::del( list );
    connect(job, SIGNAL(result( KIO::Job *)), this, SLOT(deleteTempDirectoriesDone( KIO::Job *)));

}

void
MainWindow::deleteTempDirectoriesDone( KIO::Job *job)
{
	if(job)
	if(job->error()==0)
	{
		//pas d'erreurs
	}
	else
	{	//erreur
		kdWarning()<<job->errorText()<<endl;
	}
	deleteTempDirectoriesDone_=true;
	close();
}


#include "mainwindow.moc"
